#archived-code-general
1 messages ยท Page 305 of 1
Please for god's sake, help me to understand crazy phenomenon
Output example:
Split: buttonSouth
False
<Gamepad>/buttonSouth
Why?! If pathSplit != "buttonEast" and word False approves it, how can it type action.bindings[i].path in third row??
make sure that your console is not set to collapse mode so you see the actual order of your logs. and also click the log entry in the console to view its stack trace. most likely that last log you are seeing is from elsewhere
oh wait no i see it
oh, i get it. It was because of ";" in the end of "if" . I was breaking my head for hours before i asked this on this channel and now i know what the problem! Thank you, great discord server, wery helpfull!
ah, that'll do it
your IDE should be underlining that as a warning for a possibly empty if statement. it's weird that it is not unless you've gone and changed some settings
I'm very unsure how to go about the math for this, but I want a player who recognizes an attack that is less than 0.2s into its attack animation and tries to dodge it will succeed but a player who fails to do so and dodges too late will get hit by the attack tracking. What kind of tracking math would I need to make this work?
tracking math? wdym
sounds like a simple timer
How so?
if (timeElapsed < dodgeThreshold)
timeElapsed being how many seconds have passed in the animation and dodgeThreshold being 0.2?
time elapsed since the attack started
You could also use an animation event to mark when it becomes too late to dodge
Yeah, I recently decided to just do something like this but felt it would be janky. It's fine for the prototype, but is there a more versatile long-term solution I could be using?
if (time > 0.2f) { transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetAngle, 4.5f); }
separate the decision from the consequences
decide if the player performed a valid dodge
then do other things based on that
maybe the attack can have a dodged flag that, when set, turns off tracking
also, this is framerate dependent, assuming this code is in Update: you should do something like Mathf.MoveTowardsAngle(..., Time.deltaTime * 180f)
this would rotate by 180 degrees per second
It's in FixedUpdate so I don't know how it would be frame dependent
ah, okay, then it's okay (although a bit more annoying to tune)
I'd still rather have a turnRate variable that's multiplied by Time.deltaTime
(and Time.deltaTime is set to be equal to Time.fixedDeltaTime inside FixedUpdate, so that isn't an issue)
Yep and multiplying by fixedDeltaTime also means if you change your fixed timestep it won't change the speed.
FixedUpdate CAN be delayed (and then runs multiple times to make up). It TRIES to be as close to whatever rate you set it to, but sometimes it isn't
it'll still wind up producing the correct amount of motion
In general if you subscribe a method to a delegate you should also unsubscribe it, but how (or even should) you do it if you do it like this?
You dont, you need to either store it or declare that logic in a method
You can't. You'd need to have a reference to the function. If it's something you're going to need to unsubscrie, best to non-anonymize that function
how do I changedensity in script?
And is there no way to just flat out clear out all subscribed functions in OnDisable for instance?
If it's an event you are subscribing to, you cannot from an external script. You can set it to null from the same script that has the event, but this will kinda be against the observer pattern which events follow
If it's just a delegate then yea set it to null
Ah has to be from the same class, that was why I could not do it that way before.
It is an event, even though though it technically only is called in play mode, I think if I disable domain reload it will never clear them out if I don't handle that manually, which is somthing I'd rather avoid.
Thanks for the info :)
I dont recall that being a thing, although you can test by checking the Invocation list
hi
while switching scenes do I need to keep a copy of EventSystem in the player prefab or a copy in each scene ?
Seems weird to be part of the player
it just needs to exist in every scene somehow
assuming you are using it
Oh I'm sorry I'm talking about GC allocation because a reference would still exist somewhere, but I'm unsure of how a anonymous method would react. Logic says it wouldn't mater. But I guess its always safer to remove if I can. :)
Unless the playerprefab brings the whole canvas with it.
Having Event System already in each scene is probably simpler though
I dont think this matters since when exiting play mode, everything is destroyed
It's a scriptable object, so I think that stays?
guys i am planning to add a bunch of modifers into my game and all my gameobjects have the same health script so i am adding all the conditions within the same function (shorthand, to make it concise)
is this ok or shall i split it up
Ah I'm unsure of how thatd work. Having anything other than immutable data in an SO is tedious a lot of the times
You'll want a better system than this if it grows a lot. Make a class like DamageModifier andhave a list of those
all the conditions
then in this function you can do like:
foreach (DamageModifier modifier in modifiers) {
damage = modifier.Modify(damage, ... whatever other parameters you need ...);
}```
so check the modifiers before calling the takedamage function?
no..
I'll just have to try and see, you pointed me the right way though, thanks :)
this would be part of TakeDamage
oh
@leaden ice @rigid island it does bring canvas with it , the inventory , would that make it ok?
i keep getting a warning from now and then by moving it There can be only one active Event System.
well yeah you're going into other scenes with event system already present
its up to you really, also depends how many scenes you got. You can just omit the event system from prefab, if you know the scene will contain one
if the warning that keeps poping is not a big deal (There can be only one active Event System.) then i think its easier to jusr keep it with the player
the warning is just awarrning it doesnt effect the experience at all
and only pops when the player moves from 1 scene to another ( no idea why it even pops )
cause there is only one event system with the player prefab
I guess maybe it copies the prefab in the new scene then delete the old one and close the old scene which makes 2 event system for a brief second
am I right ?
if the object is in the new sscene yes both will be in the scene
Are you using a singleton pattern for your player or something?
where it destroys itself
the right way to do this is to not put the player object in each scene. Use a bootstrap scene to bootstrap the player instance.
It can cause issues. It is warning you because it should not happen
@leaden ice @spring creek ok thanks , I will try remove it from the player prefab and keep it in each scene instead and see if that makes it better
yup , that actually fixed it
@leaden ice @spring creek @rigid island thanks โค๏ธ
@leaden ice
this is how i decided i wana do it
@spring creek public Dictionary<string, bool> battleModifiersD = new Dictionary<string, bool>();
public static bool s_ExplodingSoldiers, s_Intangibility, s_Colossus;
i have a dictionary of forbidden fruit
im planning of adding 25 of these babies
Uhh, not sure why you pinged me
Ahhhh, the static discussion from yesterday
yes lol
So that is for gamewide flags, right? That should be fine
yeh
:)
so when u pick the mods before the game starts
it changes the functionality for all classes
before u instantiate any of ur units
So, if I decide to use this method of having the character wait 0.2s into the attack before it starts tracking, how would I go about making sure it will track just well enough to not still hit the target if they dodged before then? I also want the tracking to be just as effective independent of distance between characters and to not use any external variables other than the target's position. Is there any way I might do that? Because I'm really not wrapping my head around the math I would need
How would I detect for multiple objects with certain tags and in a certain range (10 for example) and destroy them?
use a physics query like an OverlapSphere to get the objects within that range (use a layermask to filter out unwanted ones)
would dikstra's algorithm be a good choice to generate a path from the start of the level to the end? I want the path to be organic and not exactly a straight line which I know is what dikstra's algorithm is supposed to do
you could generate a path with the NavMesh system, then do something to make that path more organic
imagine dragging a ball on a string behind you as you move along the rigid path
you could even physically simulate it -- make a physics scene and simulate dragging a rigidbody along the path
(the physics scene would make it easy to simulate a bunch of physics ticks manually)
Most path finding solution that I know of uses A* which is just dijkstra's algorithm with heuristic function to optimize it. If you wanted to get more natural looking path, you could simply slightly randomize the weights between the nodes to make the "optimal" path not be straight
im doing it in 2d with tiles so i believe there are easier ways than this
ah, is this still going to be constrained to a grid, then?
yea
imagine a 200x200 map
or something like that
im trying to procedurally create dungeons
but they will be overworld so woods, deserts etc
are there any good a* libraries or do I just make my own
you could make a more meandering path by randomizing the cost of each tile a little
throw some Perlin noise on it
great thanks
note that if you're using A*, you will need to make sure you don't wind up breaking the heuristic
the actual cost to reach the goal must not be lower than the heuristic's estimated cost
otherwise it can find a suboptimal path
typically youโd post process the optimal path to make it look more natural instead of encoding the naturalism into the graph
say I want to use this for enemy pathfinding as well
will it be able to handle over 100 enemies?
If I have a list of effects to be triggered by something, where each effect would have public fields to tweak it, is there a serializable way to implement it in the inspector?
Interfaces and abstract classes do exactly what I want but aren't serializable in the inspector and I'd rather not dabble in a custom inspector for them as my last attempt was rather messy (unless there's an easy clean way)
ScriptableObjects work well, but for each altered effect with different values I'd need a new object in my assets which could add up.
The current approach I'm using which works fine is to have one effect class which contains all the properties each effect type would need and only showing the necessary attributes based on an EffectType enum. This is wasting lots of memory presumably as each class instance has each variable but it's serializable and much cleaner to deal with in the inspector which I'm willing to live with I think.
Just wanted to know if there are any better suggestions or whether my assumptions on the last solution are wrong and it isn't as wasteful as I'm thinking.
If you buy the pro version it can easily handle that on desktop (depending on the scale of the scene ofc. But assuming enemies in maybe a range of 200m around the player, no problem)
This is where [SerializeReference] is useful.
Cost of pathfinding varies greatly depending on how many nodes needs to be traversed to find the path and what sort of processing you might do.
(that is going to require a custom property drawer, though)
I use the property drawer provided by Animancer https://kybernetik.com.au/animancer/docs/manual/other/polymorphic/
actually, hey @quartz folio , does https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown work for lists of abstract types? I briefly tried it and I think I had trouble with that.
is this in the Lite version? I looked at it before but didn't end up using it as I thought I was too far in to be bothered to switch
Unsure. I didn't wind up using the polymorphic drawer before I bought the asset.
Lists may be broken. Lists and serialized references are cursed, but I could look into it
I have a custom property drawer done for abstracts but I hate it, I essentially had an abstract instance I could select the subclass for and then had a button to duplicate that instance to the list
The example code shows a Fruit[] in the code, but I think the demo video is just showing a Fruit
it worked but was awful
I use lists of abstract classes all over the place for "effect"-style design
Yeah, I fixed that in a commit that isn't on main
I love how when you add to a list using serialised reference it just adds the same reference
crunch
I forget what I did for that as it was so long ago that I actually made this extension ๐ a lot has changed with UITK lists since then
Is there an alternative to lists I can use with this? It looks nice from a glance at the repo as I don't think I can be arsed to make my own drawer
I was looking at Animancer's code to see if I could mangle it into something that uses UIToolkit
i then decided I was not going to do that
I'll see if I can look into it today anyway. There may be an easy fix
alright!
tysm, please ping me if you do but no rush
I was planning to switch to using your library (because UIToolkit support means I can make much nicer property drawers), but lists are pretty vital to how i'm using [SerializeReference]
i have Animancer in my current project exclusively for the property drawer lmao
there are no animations
I've seen some nice stuff with animancer and Odin I really wish were in base, i'm just using MyBox atm but it's worked very well
@quartz folio sorry for the ping, I presume you already know there are other libraries to do this and I've ended up using this one which works well: https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Thank you very much for offering to have a look into it anyways!
so I just learnt you can make Awake() async. What other unity methods can be made async? I couldn't seem to find info online through the docs
anything! async isn't part of the signature of a method, it changes the implementation of its body
but also, it's a bad idea to make many things async lol
well I know async tends to "grow" upwards through a project
but I thought you aren't usually suppose to make async methods void? And unity will just accept that it's async and run with it?
yes, it normally needs to spread because you return Task and expect callers to await it, if you don't you're just starting async operations without waiting for them to finish everywhere
I don't know anything about how Awake is actually called from unity, but if I try to call async Task SomeMethod() from Awake() the compiler complains to me it will be ran asynchronously.
unity isn't actually doing much here, it's all C# stuff
since Awake is sort of a constructor, you should not make it async in the first place
Unity has direct examples of making it async, so I doubt this advice:
private async void Awake()
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
https://docs.unity.com/ugs/manual/cloud-save/manual/tutorials/unity-sdk#Player_Files
it isn't right just because unity does it
async Awake won't directly cause any problems on its own, it's just something to be careful with because it's easy to make a mess with
also any time you see async void its already smelly code
Yes, and they didn't support property drawers last I checked. Which make them useless to me
According to C# docs async void should be used for async events, which I guess Awake is?
Or if they do, they do it via some harmful way that breaks everything else
oh hey, here's you explaining it, simon :p
yeah, MS originally "allowed" async void for WPF events i think and you can make the argument that unity events are sort of the same thing
sure, but I'm not going to be making a mess with it :)
it's useful to be able to have an async onClick on a button for example
ooh, thanks for the link. That's good to know, like preferring to use "Awaitable" rather thank a Task.
async void is for fire-and-forget type of things, c# calls those events in the doc, i.e. stuff that isnt awaited. the issue is that there is just very little that tells the outside world whats going on and what can be expected from such an event and what async side-effects it will have, so you should generally be very careful with it, it also has issues with exceptions.
at least in unity you get one bonus point which is that async void methods always get their exceptions logged if they throw because of the way the unity sync context works
ahhhh I see, I'm not using them where I need references at the mo so it still works in that case
sure, I'm not doing anything weird though :) So let's get back to my question, I don't really want to defend why I'm asking it when Unity itself has it in the example of how to use a part of their SDK.
So I guess since it's mostly C# doing stuff as you said @thick terrace, why does a async method called from a regular method run synchronously? What's the correct way to do that? I would assume Awake is being called from a synchronous method.
it'll run synchonously up to the first await like any async method, then you have no idea when the rest finishes
so you can actually treat the first part of the method like a normal Await then the rest is like you started a coroutine
obviously, big refactoring hazard if you move that first await lol
ah yea I get that. But I swear that I was using an async method that had an await and the compiler was warning me it would run synchonously. Something like this:
void Start() {
DontDestroyOnLoad(this);
Load();
}
void OnDisable() {
Save();
}
async void Save() {
await File.SaveAsync(); // or however you do it, i'm writing this in discord.
}
async void Load() {
var a = await File.LoadAsync(); // or however you do it, i'm writing this in discord.
// then convert a to some type of object through JSON serialization
DoSomething(a);
SceneManager.LoadScene("someScene"); // or really just do anything else, in this example this script is in the first scene which contains a spinning symbol representing the game is loading.
}
``` It would tell me that Load and Save would run synchronously. They shouldn't?
you need to actually run them in an async context to not be synchronous
are you maybe thinking of the warning you get if you have an async method without any awaits in it? it's worded similarly to that
maybe... so Save and Load should run asynchronously here right?
no, invoking an async method from a synchronous method without using await doesn't result in synchronous behavior
yes
you cant start an async "thread" with a regular method call
it's not a thread, it's a continuation posted to the sync context
there is no continuation without any context existing
Then perhaps I was thinking about that warning, but I swear it was something like that. I've done it exactly like this before, but recently in a game jam I was making a save/load system and it was giving me warnings so we just scrapped it because well it was a game jam and time constraints yk how it is
you're always in a context in unity!
Ok, perhaps I was just confused. I don't use async very much after all! Thank you @thick terrace!
Which Unity version are you on? It seems to work fine on mine. I have seen weird things on one project but I half-presumed it was DOTS
This was in 2023.2.x . I can go look at it again later
maybe I need to repro it with something more complicated than fruit
well all i can say is that i think your example just now looks OK ๐ but if you get a warning like that it usually means mixing and matching async and non-async methods and tasks in weird ways
yea i'll ask here if I get that warning again because I thought it worked like that too until I was having trouble the last time I tried it
also seriously thanks a lot for this, I'm so happy you linked that documentation page the message before this one because learning about Awaitable is awesome! Doing some background work would have been very helpful a while ago but now I know about this!
I have a bunch of lists of Vector3s for a number of objects. I want to generate a string ID for each unique list of Vector3s
I have a Dictionary in my parent object that is meant to keep track of all the known list<Vector3> and their associated IDs
trying to getkey with the List<Vector3> isn't working
wondering how best to handle this
Anyone know why I'm having trouble loading .bin files as TextAsset via Resources.Load?
Docs for TextAsset states it represents a raw text or binary file asset, however I cannot drag a bin file in the inspector, nor is loading it via script working (getting NullRefException)
I just want to get the byte[] of the file via TextAsset.bytes to deserialize it (i'm using Odin)
I'm doing Resources.Load<TextAsset>("myFile"); and I've also tried adding a ".bin" extension to that string, but no luck
you can combine the hash-codes of all the elements in the list into one semi-unique hash (checksum) of the list and then just .ToString() that
i believe the extension you want is .bytes not .bin
yea that's where I was leaning
Is the file actually a TextAsset?
No it's a .bin file
I'm new to dealing with hashes, will a Vector3 always generate the same hash given identical component values?
But I don't know how else to call up a .bin file via Resources.Load
perhaps you could also use System.GUID.NewGuid() to generate a Guid and convert it to a string with the ToString method
Then went are you loading it as a TextAsset? Ever heard of type safety?
each list is by itself a unique object, so the hashcode of the list object is also sufficient to ID them, unless you need to de-duplicate them via the checksum
I can't find any way to load a .bin via Resources.Load as I said
TextAssets are the way to load random binary data, you just need to change the extension to .bytes for unity to recognize it
Resources only supports unity assets. You can't load an arbitrary file with it afaik.
Perhaps you can put it in StreamingAssets and load it from there using C#'s options for loading a file? If Resources only supports unity assets maybe that's a good option?
I tried this but it still failed
it should, provided the floats are actually identical
in what way? in the editor you should see the type come up as text asset rather than unrecognized after changing the extension?
right. I guess I only care if the components of the list exist in the dictionary, not caring about order. If I xor the hash codes and use that as the key, that solves two of my problems right? That way I don't need to sort the lists before hand since the xor will do it
will *essentially do it
no, the xor will ofc be different based on the order~
my bitwise knowlage is poo poo lol
Sorry, I misunderstood. This worked! Thank you all, never would've guessed I had to change a file extension
yes, it's not well documented lol
only embedded programmers truly know that stuff ๐
and all the trickery around it
Chose a hash algorithm that suits you need, and apply it on each element .. and then xor all the hash's together. This will give you the same result, independent of the sequence of the elements.
I mean .. it does mention all the extensions in the docs https://docs.unity3d.com/Manual/class-TextAsset.html
that's according to stack overflow lol
good to know. would be better to know why ๐
oh, it's not mentioned in the scripting docs though ๐
Always check the manual too;)
To be fair the relevant info was pretty buried. But yes, next time I will search the entire manual and not just scripting docs. Either way thank you simonp for making me feel less dumb. Hah.
cause it doesn't matter if you do int1 ^ int2 ^ int3 or in2 ^ int1 ^ int3 it'll end up being the same thing
i think?
yes, but thats not an actual explanation
just more facts you take on authority
i bet there is a proof somewhere
proof by excel โ
what cause these - each time i delete an asset, seems like it's a post process on assets
there are a few post processes in my project
I already checked out unity.huh.how/package-manager/package-errors, and there's still package errors for my Unity project. What do I do?
Panda BT v2 broke the build! bloody thing
alright it's working in practice. it's generating the same hash value if the arrays have the same elements regardless of order
but now I have a different problem
it seems that if I have vectors that "cancel each other out" it xors out to 0
that feels right somehow
Keep in mind, hash code does not guarantee no collision, so two different Vector3 can generate the same hash code and collide.
I can live with that for now
you could just encrypt the list's hash codes and use that as checksum to fix the xor
Cool, just so you aware ๐
I just still need to be able to take an array of Vector3s and turn that into an identifier
that's deterministic based on contents
but right now an array of length 0 and ones like this edge case will end up with 0 (it's 1 in the screenshot just cause I set it to 1 initially)
add the hash of the list object itself
You can combine hash code of both the array length and each of the element.
that would make it unique to each list no? not wht i want
yea seems like that makes sense
I may need to figure out something else for the list elements instead of vertices in the future
in any case there is no guarantee that this method reliably differentiates array by exactly the properties you want
you somehat gotta work with whats possible
yea this will do for now I'll need to dive in deeper eventually
i'll backburner it
thanks guys
I came in the conversation late so don't have the full context of what you are using this for, but the collision point is something you do need to be aware of.
Things like HashSet/Dictionary use hash code as a shortbut, but they still need to perform actual equality checks because of the collision.
there are bigger issues than collisions
I'm looking for equivalancy checks in elements of the array
like xor of point-symmetric vectors being 0
so I'm open to other solutions
the best check is to check all elements against each other based on the set operations you want
I want to check to see if another array has already been registered or if a new array's contents are unique
There are plenty implementations of collections with value semantics online, shove them in a hash set and that's all.
maybe what you really need is setA.Except(setB).Any()
this is where I'm stuggling. I've been trying to find an example of what you mean
oh you know what I think i understand now
I can make it a hashset<List<Vector3>> and look up that way?
You cannot, since List<T> does not have value semantics, but that's essentially what I'm trying to tell you: you just need to implement your own array with value semantics, where a == b compares by content, then you can just shove it in a HashSet<YourEquatableArray<T>> like you would with anything else.
That requires not only you to implement GetHashCode correctly, but also the actual comparison has to be by value, you cannot skip out on the latter because hash code can always collide.
If you don't know what you need to implement/override, the easiest way is to just use something like SharpLab and look at what compiler generates with public record struct Test(string Foo, int Bar); or something.
That will tell you all the things you need to properly implement for value semantics, and you just need to swap out the hash code and equality implementations.
wow SharpLab is sweet. thanks
I'm creating a sim for optics in unity using line renderers to represent rays of light. I'm having an issue with my system. How it currently works is every fixed update it will clear out its current line renderer and create a new one based on the light that's coming into it (I'm aware of the inefficiency of recalculating everything even though no changes have been made, I'm lazy though). I'm having an issue where some objects will have their line renderers destroyed after the new line renderers are created, probably due to script execution order. Is there a way I could "time" it so that the method to clear the lines will only be called after everything in fixed update is done? A "LateFixedUpdate" of sorts
This is the intended behavior
This is the current behavior. The gizmo rays show that the calculation for the line is correct, and the method is being called, but the lines are being destroyed after they're created.
Figured it out! Just had a variable track how many frames past since it was last updated. If it was 2 or more, the clear happens. Allows a frame of leeway which is enough :)
does anyone know if I can temporarily disable FMOD?
I don't know where to find: FMODStudioModule.cpp
anyone know why when I try to copy a tilemap prefab (premade structure) onto my main tilemap through code, only a part of it copies. It's only happening for a specific prefab, my other one works fine
it seems like the chunk is getting cut off?
hey, i'm looking for a system that will allow me to apply linear motion to gameobjects given supplied source and destination x,y coords (Built-in animation system will not cut it as it has to be something that can be paused and resumed without impacting the movement)
Linear motion is very simple
Just using Vector3.MoveTowards or Lerp
Both will give simple linear motion when used properly
anyone have a suggestion
they are getting pasted in like this, hm
reading into the documentation for both of these calls, this doesn't seem to work for me as most of my movements must happen in vastly different durations (even for a similar movement)
Both of them will work in that case
You have full control over duration
I also have situations where multiple of these movements are happening simultaneously at varying durations
I'm waiting to hear a problem here
None of this is an issue
You will have to write a little code
It's not difficult code
Either attach a component to each object or track all the motions in a collection
The linear motion is simple and the pausing is as simple as a bool
https://pastebin.com/miGipUZ0
Is there any other way I can handle 2D collision between the players ship sight/field of view (Which is a 2D image, but the image itself is a circle (transparent)) and my about 625 fog tiles?
I guess this was a temporary solution
With a small ship sight, like a scale of 15, this fog collision is fine, but when the player gets to the highest ship sight they can get the fog collision's accuracy drastically drops. Fog tiles could be almost entirely inside the players ship sight before the fog collision notices they've collided
And it's not a performance problem, even on my phone as the player moves with the biggest ship sight I get over 60FPS
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I don't think my logic is right:
public AudioSource startingClip;
public AudioSource nextTrack;
private void Start()
{
startingClip.Play();
}
private void Update()
{
if (startingClip.time >= startingClip.clip.length)
{
startingClip.Stop();
nextTrack.Play();
}
if (nextTrack.time >= nextTrack.clip.length)
{
nextTrack.Stop();
startingClip.Play();
}
}
ok... I think I can make this work using Vector2.Lerp commands, but am I forced to use float time to dictate speed? my movement data contains start and end frames that dictate speed as well as xy start/finish coords
Hey guys, I'm working in the Meta All In One package and I'm using hand tracking. I'm trying to create a darts game where you just throw darts at a dart board. I have everything set up and it's working fine but I'm not able to get enough velocity while throwing the dart. I've set the weight lower, I've removed drag, etc. Does anyone have any advice on how to make the dart throw feel more realistic?
My first idea is to apply a force to it when the hand releases it but I can't find anywhere in the docs or online how to get the throw event to trigger something like that with Hand Tracking rather than a controller.
Any advice would be appreciated.
Assuming your project doesn't have a set framerate, having movement tied to frames might not be the best idea, as the speed would be different depending on hardware. If not, then you can just calculate the frames relative to actual time (eg. 30 frames at 60 fps is = .5 seconds) and just pass that in as the time.
I know movement based on frames sucks, but unfortunately, it's the only timing data I have for my object tracking sheet (unless I want to manually retrack everything) (if it helps visualise things, I basically have to recreate a situation where bounding boxes keep their position over an active video and the only data I have is the original sheet of xy coords, their start time in videoframe, their end time in videoframe and depending on the bounding box, their width and height)
15fps original footage, but 60fps new footage
Yeah if you know the framerate, it's really easy to calculate time
But if you really need it to be tied to frames, if I understand correctly, you could set a up a coroutine that has a loop that iterates equal to the amount of frames you need it to.
int frames = 0;
int totalFrames = (whatever number you need);
while(frames < totalFrames)
{
Vector2.lerp(xy1, xy2, frames / totalFrames)
frames++
yield return null;
}
using UnityEngine;
public class ShipSight : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log($"ShipSightScript: OnTriggerEnter2D: Collided with a tile!");
if (other.CompareTag("FogTile"))
{
Debug.Log($"ShipSightScript: OnTriggerEnter2D: Tile matched 'FogTile' tag");
other.GetComponent<FogTile>().Collided();
}
}
}
The first screenshot is my ShipSight, which has a 2D Box Collider with a kinematic body type, and a 2D circle collider with the correct size. The second screenshot if my fog tiles, they all have 2D Box Collider with the correct size. Each object has their corresponding script attached to them
The script I'm worried about the most the right is the ShipSight script, which I put above. Even though every collider has "Is Trigger" set to true, and each fog tile has the tag "FogTile" when they're supposed to collide, I don't receive any debug logs. At all. Nothing happens
You appear to have added Colliders to UI elements which is crazypants
It doesn't make any sense
UI lives in a completely different coordinate space
What are you trying to do here?
I'm just trying to add collision between my players ship sight (literally just a 2D image) and fog tile (more 2D images) in the Canvas.
I already have the logic, but it's not accurate, atleast when the player gets a bigger ship sight.
https://pastebin.com/miGipUZ0
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What does "shipsight" and "fog area" mean?
Is this for fog of war or something?
You would need to put an object with the collider in the actual world space area corresponding to the fog area on the map.
If you're displaying fog in your game world it should really not be done with UI elements
Sorry lol.
In the image, the fog is circled with red. The ship sight is circled with orange.
I had a map panel in Canvas that the player can explore, as the ship sight, the field of view, I guess, touches a fog tile, the images, the fog is supposed to fade away
Am I able to invoke private methods in a private class? I can do something similar with serialized variables.
what are you trying to do? what is similar about a variable
I'm trying to call a private method in a class I don't have access to. I know how to access a private variable in a private class using SerializedProperty, but I don't know how to do that with methods.
reflection if thats really what you need
https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-8.0&redirectedfrom=MSDN#overloads
I don't have access to the type since it's a private class.
just to make sure, you mean a private class like this?
public class A
{
private class B {}
}
No, it's like this:
{
void MyCode()
{
//Code to call Plugin.TheirClass.TheirCode()
}
}
namespace Plugin
{
sealed class TheirClass
{
private void TheirCode(){}
}
}```
this sounds suspiciously like modding. What is your use case?
Hi there! i'm having an issue with a worldspace canvas. It visibly is behind my other UI (that are in screen space camera mode, projecting onto another camera especially for the UI; this camera being in orthographic mode.), the order in layer is inferior to but the raycasts are blocked by the worldspace UI anyway, which is weird. Then, i thought that if the plan distance was too far away, maybe it was messing with some things too bc the worldspace UI was technically in front of it in terms of coordinates, so i changed that in play mode but still nothing. any ideas?
I get this error: CS0122: 'TheirClass' is inaccessible due to its protection level.
I'm trying to create an editor tool that utilizes Unity's ProBuilder plugin.
i am casting a raycast to reveal a object if its detected by my spotlight
is there a way to handle a sort of OnExit for the raycast?
๐คทโโ๏ธ i copied the exact setup you shown for the class and method
It could have to do with unity's assembly definitions, or MyClass and TheirClass being in different files.
Guys I'm having 2 cursor-related issue here, like, seems like it's cus I'm using Linux-
The first issue is kinda resolved, and is that when locking the mouse, the mouse does visually reveal at the center after unlocking, but Input.mousePosition heavily disagrees and is higher up to the right.
I fixed that one by making a cursor manager that returns the actual screen center if it's locked.
The second issue is that Input.GetAxis did a great job at overshooting whenever dealing with locking (and unlocking?) the mouse, and uh... Honestly I ain't got no idea how to fix this one :(
I'm guessing that it didn't like the fact that the mouse basically teleported to the center of the screen.
And the second issue's kinda a game breaker for me cus uh, I force the player into some sorta FPS mode when drawing a bow (No alternative to this system without doing major changes to the game)
Might ask me why I don't turn a blind eye to this issue (Since it appears to be linux specific) or something... Well, I just don't want every linux user struggle thanks to this bug
Also strange thing that when I searched for it it's an old bug that was supposed to have already been patched back in Unity 2019 or so, but here I am, on Unity 2022 xD
I can't get the turret to slowly rotate to target something is wrong:
transform.position = parent.position;
// Get the rotation of the car in quaternion form
Quaternion carRotation = car.transform.rotation;
// Calculate the rotation to apply to the turret based on the input
Quaternion turretRotation = Quaternion.Euler(0f, aimInput.x * rotationSpeed * 90f, 0f);
// Combine the rotation of the car with the rotation of the turret
Quaternion combinedRotation = carRotation * turretRotation;
// Apply the combined rotation to the turret
transform.rotation = combinedRotation;
// Calculate the rotation to apply to the gun based on the input
Quaternion gunRotation = Quaternion.Euler(-aimInput.y * 90f, 0f, 0f);
// Combine the rotation of the turret with the rotation of the gun
Quaternion combinedRotation2 = transform.rotation * gunRotation;
var desiredRotation = Quaternion.Lerp(transform.rotation, combinedRotation2, currentRotSpeed);
goGun.transform.rotation = desiredRotation;
Please properly share your !code and explain what is happening instead
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(serializedObject.FindProperty("model"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("name"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("description"));
EditorGUILayout.PropertyField(weaponType);
WeaponObject weapon = target as WeaponObject;
//Based on the selected weapon type, display relevent properties
switch(weapon.type)
{
case WeaponObject.weaponType.Nothing:
EditorGUILayout.LabelField("Please Select a Weapon Type", EditorStyles.miniLabel);
break;
case WeaponObject.weaponType.Repeater:
DisplayProperties(repeaterStatsProp);
break;
case WeaponObject.weaponType.Ballistic:
DisplayProperties(ballisticStatsProp);
break;
case WeaponObject.weaponType.Cannon:
DisplayProperties(cannonStatsProp);
break;
}
serializedObject.ApplyModifiedProperties();
}
// Runs a iteration through the provided prop so it can generate each child (variables) of that prop in the inspector
void DisplayProperties(SerializedProperty prop)
{
SerializedProperty iterator = prop.Copy();
bool enterChildren = true;
while (iterator.NextVisible(enterChildren))
{
EditorGUILayout.PropertyField(iterator, true);
enterChildren = false;
}
}
I've been at this for quite a bit and need some help. I am making a Custom Editor that will change the values below "Weapon Stats" with one of the 3 classes in my switch method. It should be iterating through that class (for example, RepeaterStatsProp) to paste only those variables. However its been pasting both the variable in it and BallisticStatsProp and CannonStatsProp.
^Weapon object in the thread
as you can see it disables the box colliders but doesnt switch the tile when i jump
Can someone please help with this problem?
Dont cross post please
Hey guys, TMPro -> sprite's from rich text via TMP_SpriteAsset that is in TMP_Settings. When i change the default sprite asset in TMP_Settings in runtime, my sprite's refresh only after scene reload, i can bypass this by calling TMPro_EventManager.ON_TMP_SETTINGS_CHANGED(); but that works only in editor. Do you know any other way to refresh settings in build version?
Guys I am trying to figure something out and I'm not sure how to do it. I have a 2d game which is Gona be isometric(although I haven't made the sprites and background yet). I want a rain of arrows to fly in from off screen to the target. I'm thinking there's only 2 ways. Instantiate like 100 arrows make them take an arc trajectory to the target and destroy them within a range or do something like rain with the particle system which would be quite difficult
Instantiating all the arrows doesn't seem feasible though
Pool em
I am already pooling like 50 for my archers normal attacks
If it's just a radius of damage and not per instance youd only need to do a single overlap physics query over using multiple colliders
I'm not Gona do collision detection
I'm only using them for the effect and make the targets in that area take damage over time with some rng
you could do the rendering yourself and have a single componet that renders the same mesh 100 times, then you'd just need an array of positions/rotations
that's basically what particles is, but if you need more control it might be easier to roll your own
Vfx graph good at this assuming the terrain isnt complicated, or by generating a sign distance field of your levels
Thus gpu computing everything
Haven't used it before
#1222475780987293737 message
My most recent project does similar with the fire rain effect
Single physics query, 0 colliders besides raycasting the point
Found it. Just needed to use contains on my iterator.name to stop when it sees a class name such as to contain "Stats"
Though a better solution would be acccessing its property shown here. Just got no idea how to call that. PropertyType and path don't seem like it
oh wait ๐คฆ Thats my own Debug.
@latent latch I guess I could do something like that but it's not as impressive as watching the arrows fly in from off screen
You can do anything you want. Thats an example of multiple particles pooled without using colliders
If you want colliders, use shuriken default particle system. You still can do similar without colliders using default, but it would be cpu driven (still fine idea)
Oh so that wasn't the particle system
I might pool the arrows I'll see
At the moment in my game I am having trouble syncing the pooled arrows in multiplayer
For the basic attack
Any tips on creating a connected water/swimmable collider consisting of several box colliders but treated as a single collider?
Feature Code
Meshcolliders don't work sadly
Volume code
Why dont mesh colliders work? Also you can put multiple colliders on the same object and they will act as one
Anyone?
hey everyone! are there any services that build from unity to ios for you that you know of?
do not cross post
When standing on a moving platform, the platform moves the player and objects using this script. It moves the player using the line at the bottom, and rotates the player using the stuff above.
I need to somehow get the difference between the rotation last frame and rotation this frame, and turn that into a float to replace the "_rotationSpeed" i used before. I'm just unsure what Quaternion calculations would be fitting for this
I'm replacing the _rotationSpeed thing because I won't always have a consistent or constant rotation
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I tried inputing the eulerangles in this, and it always gives me 0,0,0,1
I am having a jittery movement idk how to fix cause i tried so many things but still it is there
here is the code- https://gdl.space/azuxopocub.cs
Here is the video and some pics of some settings-
huh ? euler angles dont have 4 numbers
How is your camera follow working?
the issue is most likely that your camera is being updated at a different rate than your rigidbody
cam movement is smooth
FromToRotation is for DIRECTION vectors not sets of euler angles
9 times out of 10 the issue is due to how the camera updates. please provide details when asked about something instead of making assumptions that it works correctly
cam mov script
also ur printing quaternions instead of eulers..
which is prob not ideal
oh
You could convert your rotation into direction if you want, but using rotatetowards might be better at that point.
Input.GetAxisRaw("Mouse X") * sensitivity * Time.deltaTime;
well there's one source of stuttery camera controls. don't multiply mouse input by deltaTime
you're also updating the camera in Update which is potentially before the interpolation on the rigidbody has updated the object's position.
Your camera should be updated in LateUpdate to help avoid such issues
ok
thanks
also obligatory: use cinemachine
Yeah cinamachine has some extra settings for execution ordering
ah wait, they are using cinemachine, but rotating it manually for whatever reason
followTransform.transform.rotation = fRot;
when you modify the transform of the player directly like this it breaks interpolation. You're doing it like 4+ times in the script
i tried rotatetowards, it does make the player rotate, but increasing in speed forever seemingly
not sure if the maxdegreesdelta being zero makes any difference
ohk
but the rotations r smooth only the jumping moving around feels jittery
yes you are breaking the interpolation the way you are rotating
rotation needs to be done via the Rigidbody
ohk
for anyone searching keywords in server message history, i solved it with Mathf.DeltaAngle
any idea how can i do the same its bit confusinf for me any points
Yes like I said use the Rigidbody to rotate
i cant quite get it
Instead of transform.rotation = ... try rigidbody.MoveRotation(...)
ohk tq
@somber nacelle @leaden ice @hexed pecan Thanks ur advice worked
new cam mov script-https://gdl.space/aqapeteqoh.cs
now the movement feels smooth thanks
you're still multiplying your mouse input by deltaTime. mouse input is already framerate independent which is the point of the deltaTime multiplication when used with other values. by multiplying it by deltaTime you suddenly make your mouse input reliant on the framerate again causing stuttery rotation
although i don't see those X and Y values even being used anywhere ๐ค nvm i see it now
so i should not multiply it with deltaTime?? will fixedDeltaTime be fine or no need?
no, do not multiply your mouse input by deltaTime
you will need to reduce your sensitivity variable by a factor of 100 after removing that multiplication too
but even if i do multiply the rotations are smooth
and i dont then also
Then leave it in and let your players experience the potentially stuttery movement ๐คทโโ๏ธ
ok understood
You don't see it, because you're testing it out with the same frame rate. If you were to test it with, say, 30 and 90 frames per second, you would notice the rotation's sensitivity being 3 times greater in the 1st case, as your X and Y values are constantly being divided by 30 and 90 in the 1st and 2nd cases respectively
ohk
thanks
That's why you should remove it to avoid this kind of behavior, the same way you use Time.deltaTime when changing the position
thanks man
Anyone out there have experience using serial ports? I'm trying to understand how the baud rate works. It seems like whatever I set it to, the value is ignored. I'm trying to determine what the actual rate is
what kind of serial port RS 232 ? RS 422 ?
USB connected to a microcontroller
not even sure you can set the baud on USB, I think the devices are supposed to negotiate it
That's what I keep seeing, but I can't figure out what that negotiated rate actually is
the device communicating over USB is communicating with 6 other devices over Serial, and I'd like for the baud rates to match
it will depend on the implementation level of the USB devices. Do they all match?
There is just the one device connecting via USB. The others are connected to that device via hardware UART
Or well, a mix of hardware and software UART
I asked this a day or two ago, but it got sorta covered up.
Just wondering if anyone has experience in designing very modular plug and go character controllers. One that can add abilities on the fly and remove them too, like plugging and unplugging components essentially.
I have all my components coded up and they work fine, but when they intermingle they have certain issues. Ive overcome this temporarily by having a massive amount of spaghetti code where in every component I check for other components and disable them when I need to and then re-enable them. This is whatever, but I was wondering if anyone has sorta, like a smarter way of going about it.
Like for example, my jump component handles yVelocity, but when I add the fly component, I have to turn off the jump component when the fly component is actively flying, and then turn it back on when its not.
This sorta specific management of other components causes me to have to go back and edit a lot of code when I would much rather have it be hands off once its set up.
Any advice would be great
Use events and (un)subscribe functionalities rather than enabling/disabling components.
sure, I can modify it to do that. But that doesnt particularly get rid of the sorta issue I ahve to tackle of knowing which components to turn off when and where.
Like I would still have to add code to fly to unsubscribe from jump, slam, charge, etc or whatever other behaviours
The manager would be in charge of that. For example, if something were to want to override movement completely they'd call a function from the controller manager where that function would simply remove all other functionalities and add the wanted movement. The same would be applicable with component base operations but I couldn't imagine why a person would want to do so with components unless they're implementing everything in the Update methods.
I've poked at this problem a few times
I'm actually about to deal with that properly, actually. My main project has a Locomotion class that various kinds of locomotion (currently just humanoid and freecam) derive from
in this case, you'll only ever have one locomotion at a time
so that's not quite your problem
(the issue I'm having is figuring out how to provide input to every kind of locomotion, both from the player and from AI characters)
Right, I have a non-physics character controller. So sometimes outward forces also have to override all control
ill look into some manage class to atleast be able to have my hands off the code internal to the controllers
I dont use the update methods directly, I have an update method called via a parent controller. Cuz the order of operations matters so I have some defined operation layers and orders that ensure certain controllers fire first
https://gdl.space/inohetawih.cs
Hello everyone! I'm working on a 2.5D game that's essentially a 3D game, but it's shot from a 2D-like camera perspective. In the game, a rocket launches and continuously moves right, dodging meteorites along the way. Now, I want to add enemies that appear on the right side of the rocket and move along with it, maintaining a consistent distance. The goal is for me to be able to shoot these enemies. However, I'm encountering an issue where the enemies try to position themselves to the right of the rocket but only do so for about 2 seconds before they stop moving and just stand still. Does anyone have any ideas on what could be going wrong and how I can fix it? Thanks in advance for your help!
Delete your other post if you are moving channels

Cross-posting is not allowed here....

Alright, just trying to help you ๐คทโโ๏ธ
The issue with cross posting is that its confusing, say you get help here, and then 4 hours later help from a different channel but you already got a solution - its less about "policing" and more that if your question is in 1 place then it lessens confusion and keeps the topic of the question within a relevant channel
Inb4 "quit yapping bro"
Yes, well then I'd rather delete it in the beginners chat when you see that it's no longer about programming at all
That was going to be my next step ๐คทโโ๏ธ but if you'd rather I butt out, I certainly will. Best of luck
@spring creek Yes, well, I have now deleted it from beginners. If you would like to help me, I would be there
Quit yapping and help him already bro
I mean it technically is a beginners question, also with some debugging you can easily figure out what's wrong
Unfortunately I can't manage that and I find it a bit more difficult as a beginner to program a bot
want to add enemies that appear on the right side of the rocket and move along with it, maintaining a consistent distance.
unclear to me what this even means
which rocket?
How do you do that black bar thing on discord?
Like where you highlight text someone said
oh like quoting ? >
some quote famous
wait navarone i make a video
OK can somebody please give me a sanity check on a new project?
The idea is that there are various "facts" (floats) that can be "learned" with "imperfect knowledge." Facts are observed by sampling a random distribution having the fact as its mean. More samples gives you better knowledge.
Anyway, the facts are implemented as floats boxed into a Fact class. new-ing a Fact generates a handle and registers the fact into a main registry of facts. The purpose of using a registry is so you only have to pass handles around, and can look up facts from any place in code. It also helps clarify ownership, which C# is less good at than some other languages (as far as I understand). I figured this was better than passing references to floats or whatever around the code, or finding the owner instance of a fact and asking for its value, or whatever, which I feel could get messy. Instead, you could just search the central registry for whatever "fact" you needed.
My fear is that I am writing FizzBuzz Enterprise Edition and that I should just scrap the registry/handles and pass around some central repository that stores floats, or that there may be some simpler way to achieve this. Any thoughts?
would anyone happen to know why my lighting might be different when loading the scene directly and changing to that scene from another one?
well, nivida geforce is not working idnt why
i cant make a video
not a code question. but pretty sure this is a known editor bug. you can ask in #archived-lighting though if you want more info
In my 2.5D game, a rocket is constantly moving right through space at a speed of 10 km/h, represented by an oval object in the sketch. During the game, an enemy (represented by a circle in the sketch) appears at a fixed distance of 9 meters to the right of the rocket. The enemy is programmed to move synchronously with the missile, both horizontally and vertically, to always maintain a distance of 9 meters.
As the player steers the rocket up or down, the opponent follows this movement in real time, but always remains positioned in front of the rocket, never behind it. This allows the player to shoot at the opponent while simultaneously navigating and avoiding other game objects.
The challenge is for the opponent to precisely follow the rocket's movements while maintaining the set distance to create a dynamic and reactive gaming experience.
Hello! Has anyone here experience with litenetlib? Iโm making a board game turn based and using it. Iโd like to talk a little bit
It's a bit vague what's actually going on here, maybe share some code for insight as to what the structure looks like. Overall, this system should be easy to use by other systems and thats all that really matters. The implementation shouldnt change much of how other classes use it
Is this an AI generated question?
Is there even a question here, it's pretty trivial to have something always be at an offset.
Hey there!
Trying to make a scene with a lot of cubes (up to 100k).
I would like to do some GPU instancing on them but I have two questions about that.
Is the GPU instancing the same thing as the (Hierarhical)InstancedStaticMesh from Unreal ? It seems easier in Unreal because it doesn't need any shader code..
One more question - Can we do raycasting on a cube instanced via GPU ?
Thanks for your help! ๐
ok. i guess aiming for ease of use will be the goal then...
Pretty sure you can draw gameobjectless mesh using Mesh library instanced methods, but that means no collider through conventional means, so then youre creating the aabb manually too I guess?
Could do combine and mesh collider after generating and using closest point method of the raycast
Not sure if it's better to do individual box colliders though
pass around some central repository that stores floats
How do you decide which fact you're interested in this way?
would you just hard-code it, like...
public bool MakeDecision() {
return factRegistry.GetFact("Foo") < 1;
}
I guess your question is about which of these two things you're going to do
Debug.Log("My understanding is: " + fact.CurrentValue); // fact either contains the value or knows how to look it up
Debug.Log("My understanding is: " + registry.GetValue(fact)); // fact is just an ID
Is that right?
I think that's basically the question, though I think the second example would be more like what you said above "factRegistry.GetFactByOwner(owner)" or "factRegistry.GetFactOfType(type).Where((fact)=> fact.owner == owner);" or something like that. basically i think the question is whether to pass around the facts themselves or whether to use information about the facts to retrieve them from a registry. i'm thinking this is kind of an ad hoc database. the game will have a bunch of information screens that display lists of various fact containers in the game and i think doing that with hard references to facts will be more difficult than having the central registry.
I want to make the sound distortion effect that happens when a blue screen happens. how do I do that?
what sound distortion effect?
the last audio thats been playing repeats again really fast making a weird crash effect. I dont know what its called but it happens hen you get a bluescreen while an audio is playin
i dont know what its called
Hey i upgraded the SerializableHashSet<T> https://gist.github.com/YunusYld/fe5f195f7781c649a5acbc34a97400b0
It works great until going into play mode. When i click at Play Mode, it gives me null reference of "parameter name: array" just one frame in line 50 and it works great after it. It seems Clear() method at the background tries to reach the array. But array coming null because the array of **HashSet **is not serializable.
Any ideas to solve this? Yeah Try Catch works but bet i do something wrong so i hope i get answers from your wisdom
https://www.youtube.com/shorts/JQff6fOI8Vs I found effect here but I dont know its name
the distortion
Uh it seems you need to master the creation of sounds a little instead of coding
how?
ohh not exactly distortion , same effect stuck
yes how do I do that?
Should i go with tryf? I hate serialization things so annoying
this is more of a #๐โaudio question
its a common effect you can do with some dj / daws but idk what its called exactly
you basically set the loop repeat to be very close to each other
but the main problem is that I dont know how to get the current audio
I can get the whole track but not the exact part where its playing at the moment
in code ? this gives playback position if thats what you need idk how you would loop a section like that in unity
https://docs.unity3d.com/ScriptReference/AudioSource-time.html
You'll want to repeatedly reset the playback position
Audio data goes into a ring buffer. If no new data is written into the ring buffer, then the audio system will keep playing the same short bit of audio over and over.
guys im losing my mind
Hey guys, is there any real reason to use js for cloud code besides that you want to?
from an initial look it seems that using c# is just easier
Which "cloud code"?
UGS Cloud Code
I have not used Unity's, but have used other serverless functions of other platforms. Serverless functions is one of the places where C#/.NET are still somewhat playing catch up, both because of the big bundle size and long cold start time, and in general most of the backend ecosystem is made for monolith. Technologies like NativeAOT and minimal API are recent additions to .NET to improve things.
I saw the warnings about cold start times, but I couldnt find any actual timings
You can probably look at some benchmarks of AWS lambda cold start times and get a good idea.
NativeAOT is a giant step forward to improve cold start time, and that only happened recently.
Looking that up, 500-700 ms is not terrible for me I don't think. Would that cold start time be something like per function, or the entire module?
The entire serverless function, once it's warm subsequent requests hitting the same function will not suffer from the cold start anymore, but that depends on the infrastructure of the cloud platform. I would think UGS probably is just repackaging and reselling AWS or something with a markup.
according to unity staff on the forums it's an in-house solution built from the ground up ๐คทโโ๏ธ
but I can't imagine it would be very far behind AWS's timings
Best to test it yourself then, since different cloud infrastructure can do things differently. If you are not locked into Unity's, you can always evaluate other cloud platforms.
Since it's my first time dipping my toes in these waters Unity feels safer and easier, and because it'll most likely be a game me and my friend release (after years of game jams and such, not just starting thinking I can make it big haha), I would like to stay with Unity for now.
I use Cloudflare Workers for a project and it was very nice that my code runs wherever the client is, so issues like "my function runs on a data center in US and clients from Asia gets ridiculous latency because every request has to round trip half across the world" don't exist.
since you have experience with it, looking at CloudFare's pricing for Workers, it says 10 milliseconds of CPU time per invocation, but no charge for duration? So does that mean for free I'm limited to only 10 ms of CPU time?
Per request yeah, but it only counts actual CPU time. Eg if your worker does something like "query from database and return a number" that's basically 0 ms no matter how long the database query takes, because that's network time and CPU is not doing anything.
ah well that's good. Cloudfare does seem pretty good, I'll probably try it out next time depending on my experience with UGS Cloud Code. But it does sound like I might want to use js based on the longer cold start times you mentioned for c# if it's per function. Thanks for the help!
Np. If you are comfortable with C# then it's completely fine to stay there, you might have more limited options in terms of cloud platform that can run C# serverless functions, but it's not like JS in cloud is all sunshines and rainbows either. Having options is always nice.
When I try to set a boxcolliders size to the rect of an image that is being affected by a content size fitter, it is always being set to 0, is this a limitation or am I doing simething wrong
I'll at least try JS. I know basic JS, by no means an expert, I'm willing to learn though and at least try it. Maybe I'll even use a combination of both, JS for easier more common stuff (where I can) and c# for more compicated stuff (where I fail with js)
An image is 2D a box collider is 3D, though the Canvas will treat every object as a RectTransform, which already has a Bounds or Rect associated with it, you could probably use that information instead - though, why might you need a collider for UI objects?
I am making a item label system similar to diablo/poe and need the labels to push each other so they dont overlap. I figured it out though, you have to use preferedwidth
Is there a better, more error proof and more readable way to do MySQL in C#?
I'm now just manually writing the SQL as a string, which has 0 error checking.
Either write your queries in separate .sql files and load them in or use linq to sql
any preference? or are both options good?
separate .sql file seems easier?
don't know what linq is ๐ฆ
If you ask me LinQ to SQL is the preferred way of doing it https://www.bytehide.com/blog/linq-sql-csharp
You are doing this on the backend right? Never ever ship your sql or db connections to the client
yeah ๐
Yeah this looks very interesting, thanks! ๐
Is some kind of component I can put on a gameobject to show to me as a marker just so I can see it in the editor
do you mean icons?
I mean for example when you create a light it has this cool image that only shows in the editor, so i want somthng like that for my invisible objects
Why not the transform gizmo?
Could the collider outline work?
That is the first thing need to lose to become a dev
You can draw whatever you want in OnDrawGizmos
Thank you for answering Mao! ๐
I'm not sure, I will have to make some tests hahah
Hello guys, I am using the standar third person pack for character control in unity, as it is charactercontroller based, for physics, it comes with its own script BasicRigidbodyPush which adds force to the rigidbody object like a cube or something, problem is, as it is not based on unity's own rigidbody physics, it runs slow on slower devices, and I know you would say that Time.deltaTime should fix this, so I did try that but it made it slower of faster devices and faster on slower devices
how can i debug stuff like tileswaps in unity
you can update time.timeScale by setting it as a variable right? Its ignoring a line where I set it from the below variable, but not when I just do = number
time.timeScale = timeVariable; //timeVariable = 2f
maybe timeVariable is not the value you want?
Idk but you could trouble shoot like this
float t = 2;
time.timeScale = t;
Mapper Buckets of HashSet<T> was returning null because it gets deleted when entering the play mode if your all Enter Play Mode Options's Reload Scene and Reload Domain set to true or Enter Play Mode Options itself set to false. In case if someone face this problem in future, the fix is: do not derive from a collection if you wan't full control over it and feel free to use the code ๐
I did try a few variations of that but had no luck - at some point it fixed itself through various experiments - appreciate the help regardless :)
Oh okay, do you know what fixed it?
I think it was something to do with me setting Time.timeScale = 2f at the start of my script, and something about me reloading the scene, and the line up the top [which shouldnt be effected cause it was in an if statement] might have somehow reset it back to 2
there was a specific check to make sure it wasnt redoing it again but it I probably wrote it wrong lol
Hey, anyone could help a little. I'm having a problem with aligning dice to selected side. When function is called it rotates towards "toSide" or one opposite to that.
Getters are fine and transforms are correctly attached.
Dice has graphics component (child) that should get reoriented fromSide that it got simulated with toSide that i want to re-simulate it.
private void Reorient(int fromSide, int toSide)
{
Debug.Log($"Reorienting from ({fromSide}) to ({toSide}).");
Vector3 fromDirection = _diceModel.DiceSide(fromSide).localPosition.normalized;
Vector3 toDirection = _diceModel.DiceSide(toSide).localPosition.normalized;
offset = toDirection;
Quaternion rotation = Quaternion.FromToRotation(fromDirection, toDirection);
Transform childTransform = _activeGroupRoot.GetChild(0);
childTransform.localRotation = rotation * childTransform.localRotation;
}
Sides are put in centers of graphics dice thus creating localPosition direction vector
Hey, does anyone know what would cause the "source file could not be found" bug?
Unity is telling me that it cannot find a file, but the script is literally exactly where it says it is in the directory, and it's being used by game object prefabs
It just randomly started throwing this error now I'm kinda stuck
Try Ctrl+R to refresh
If that not helps, right-click on script directory and reimport
*In Unity editor
reimport did it, tyvm!
Next time don't let your editor instance drink and drive :)
it has a mind of its own. I need more shackles
Is it possible to get the string value itself of a FloatField in a custom inspector? I want to detect the difference between the developer deleting the content of the field and the value actually being 0.
is there a furom channel for my long and complicated problem
I guess you can post it here with a link to your !code using one of the following websites
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Maybe create a thread in the relative channel if it's too large and redirect to the thread from the specific channel (don't cross post) if the post gets buried - not too often though (spam).
Yes, Unity also has the forums if you're needing more dedicated suggestions/assistance/feedback.
i have a problem in the build so i will make a thread
This is the coding channel
"Could be" or "is"?
i really dont know because this problem is very mysterious
Maybe ask in #๐ปโunity-talk providing the behaviors
maybe instead of talking about talking about the problem, start talking about the problem :|
i did like 3 times
and still didnt get a solid answer
so i will have to make a thread now
Tile swapping in editor but not build
i asked in every single channel
code that is
Hey guys!
I need to make a warehouse logistics viewer in 3D (so basically to represents pallets in racks).
There can be between 1k to 100k objects but they can only be one of two meshes (Pallet or Rack).
Nothing moving; the only interaction will be a raycast from the camera to the pallets.
I was wondering if DOTS would give me any benefits in such situation ?
I read a lot about it but most articles I found are about animating a ton of objects more than just instantiating
Thank you for any hint you can give me ๐
can someone help me there is a problem that is happening that i just cant figure out at all
it makes no sense
i want to call so i can show via screenshare
I doubt anyone would want that
why isnt there a call chat in this server
If it's something you can't describe easily, at least show us a video of it
ill show the code and explain waht is happening
Because no one would use it for helping purposes, and these is no off-topic either
It's just better if you actually describe your problem or post a video so that everyone can see it and answer if they know how to fix it
Just describe the issue you're having
It's been suggested many times before and the results usually directed that they were difficult to moderate and unnecessary as you could just dm someone who is willing to personally help you (not common).
so i have the explode function and the takedamage within the health script
and the deal damage on another
in my game i have 1 gameobject attack the other, 1 on my side and the other on the other client
the gameobject dies, it triggers explode which calls deal damage and then calls takedamage
i put debug logs in each function to see how many times they are being called
explode triggers once, deal damage triggers once, but take damage triggeres twice
howver it doesnt have the (2) on the rgiht side of the log, they both come up individually (1) and again (1)
in this order
how is this possible
take damage is being called twice
it must be to do with the rpccalls or something but when call dealdamage with the normal attacks take damage happens once as it should
everything is working with choosing a player and all that, but I don't get why I get this error
A GameObject with the tag Transition1 doesn't exist in the scene
If you can't find the object, the get component call will fail and throw that error
yet it do find it on the other scene when i go to there by clicking on the button
I have been having a weird issue relating to my movement on the player
when you move the camera while moving, it seems to cause things to almost stutter
when you don't touch the mouse, the movement seems smooth and fine
It doesn't on the current scene though. You should have a GameObject with the Transition1 tag, otherwise you'll receive an error
but when you move the camera in a specific way, it seems to make your acceleration weird
The solution would be to have a means of not needing to find it - ensuring that it's always present (Singleton Manager, proper sharing of references, whatever).
but i did the same thing with the others and everything is fine
The band-aid solution would be to separate the Find and Get Component calls into two statements where you'd not do the Get Component call if Find failed but this will likely have consequences if the object was necessary but missing - bug tracking headaches aren't too far away with band-aid solutions.
band-aid solution?
var transitionObject = //Find
if(transitionObject)//Not null
{
transition1 = transitionObject.GetComp...
//do other stuff with transition1
}```Understand that if anything else needs `transition1` to not be null, they'll throw an error as well.
why transitionObject? (even though I don't have that?)
To temporarily hold a reference of the found object.
If nothing were found, you would not want to do the get component call or operate with transition1
Which brings up the real question and problem: why was the object missing?
because in the first scene is not there, but it's in the second theme, even the camera also have getcomponent and it is working
The error is suggesting that it's not in the scene.
If you can fix that, you'll not need the pesky guard statement (referring to the if not null, do stuff statements)
then I don't know what to code in
I mean like then I don't know what to write in
because this is all I got and the fact that everything works while there's an error
Greetings, all. I just have a quick question - how to check if mouse is moving clockwise or counter-clockwise? Is there any function for that, or perhaps a script online?
You don't really need to write code yet (we know it's not progressive tangibly but it's necessary). Try to figure out why the wanted object isn't present in the scene you're expecting it to be in.
Your best bet would be to
else you'd just need to track the delta direction
I don't know why, it works for the mainCamera but not for the transition one, because the transition image for player 1 is only in the other scene. I just don't get it that it works for the main camera, but not the transition1 in the other scene
Was the "Transition1" object in the scene when these statements (the Find + Get Component method) were called?
There isn't anything wrong with the code (logically). It's simply that the other object isn't in the scene.
not for the transition1 in the level select scene because it's for the playable stage scenes
So you can't reuse those lines of code for this other scene that doesn't have the missing object. Maybe consider using the guard statement pattern as suggested above or uniquely separate some of the logic in the code you've shown. Ideally, you'd want to decouple the code from the persistent object and have it be managed in the scenes that they are present in. This would ensure they're usable in those scenes.
so I'm supposed to like put it in there like the maincamera there whil serving no purpose at all and that there's other maincameras in the next scene and another transition?
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Is there a way to switch on/off custom pre-processor directives for editor play mode? Project's too large for a full build, but there's some stuff I'd like to toggle for performance testing
What object were these lines of code on?
hmmm..... != null
I'm referring to which object in the scene hierarchy were these lines of code on? They're statements in a script so they ought to be a component on an object in the scene or some scriptable object instance or pure c# object (static whatever). @cloud python
also, all these are in the other scene, not in the same scene
What's the name of the class? What objects in the scenes have got this script-component attached?
Depending on the Unity version, you could do some "incremental" builds. As far as I'm aware, older version of Unity required you to explicitly start a "Script only Build" (which in my experience is already much faster).
Besides that it could be worth it to implement something that reads files in the StreamingAssets directory and adjusts the initialization accordingly. This way, you can test different combinations without rebuilding the project - and this would also take effect in the editor. (It might be even better if you could toggle things at runtime, but this could become even more effort to implement.)
Regarding in-editor: "the" way to toggle pre-processor defines would be to adjust the player settings. You could do some editor scripting so you just have to press a few buttons, but in any case you'd have to deal with local changes to the project settings.
If I'm not mistaken, you can also define preprocessor-defines in the msc.rsp, but it's been ages since I used it, so I don't have a documentation link at hand. =/
So each scene has a Player Manager Object?
Or is this a Singleton object?
yes
So if you've got multiple unique instances of this manager and nothing's really moving (persisting, don't-destroy-on-load, etc) between scenes, perhaps consider referencing the fields from the inspector?
also you kinda ignored my question here
I mean no
so that it won't be anymore errors?
I'm not sure. You're the level designer. If a feature is unnecessary, you can either have it inactive or not in the scene. This won't fix your referencing issues though. You need to separate the code to prevent the execution of functionalities not present in particular scenes.
yet I don't know why it's like that
So, instead of having Find and Get Component everywhere you could simply do the referencing from the inspector.
After properly addressing the references, you can determine what's absolutely necessary on every game manager script and what's optional per scene.
You'd decouple the unique functionalities into a different script and add that as a component on whichever game manager object that needs it, relative to each scene.
Communicating across different scripts might seem scary at first but it isn't really all that difficult once you're able to properly reference stuff
I have the variable and reference in the script, how can i reference in inspector?
Either have the accessor as public or add the c# attribute [SerializeField to make it visible in the inspector (they'll be serialized)
decouple the unique functonalities?
like this?
but still getting errors
For instance, Transition1 isn't present in particular scenes so you ought to move transition1 and all statements directly using it to it's own script - maybe you'd be able to couple a few functionalities or all of the remaining functionalities if the scene game manager objects only differ that little.
Can you share the script? !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh of course the errors won't immediately disappear. You're just beginning the refactoring process.
Hey! I feel like I'm missing something simple.
So I have this code that's called
From Enemy here
Yet I get this
There should be a rigidbody, no?
(here you can see it is indeed called from that gameobject Flyer (Enemy 0) )
Alright, so this is a Singleton object - semi, without ddol. @cloud python Which is fine but likely unnecessary.
nvm my question, just figured it out while explaining it
was supposed to be _rigidbodyforvelocity = GetComp...
but this one is really needed in the world select scene for other scenes. what's so unnecessary about it?
Nevermind it's a ddol. I'm getting on a workstation.
oh, workstation?
Disable collapse logging and show us what line is 50.
i replied to myself above, typed .GetComponent insstead of = GetComponent ._.
It looks like other than life and the game over functionalities, everything else can be done from other objects inside the specific scenes.
oh?
Hello,
I have a system where the player controls a rig that several units are child too. Units die and get added during gameplay, and so I have a script that sorts units into a formation dynamically by moving units between 5 slots in an arrow shape.
In a little more detail, the sorting is done by changing units parent transform between empty gameobjects that represent each slot. This works perfectly fine. I just want to make it so that the sorting is animated or visualized instead of units blinking instantaneously between spots. I think I have a rough idea for how to make an object move gradually, but I'm not sure how to do it when the transform is just changing the parent object and making the object move to the parent's transform.
This is a sample of the kind of code I have for moving units between slots:
if (delta1Trooper == null && delta2Trooper != null)
{
delta2Trooper.transform.SetParent(delta1GO.transform, false);
}
Would doing something like adding some kind of DeltaTime clause in there be good enough? If so what would that look like? I think I would be able to take it from there to make the transform also speak to the unit's animator to trigger the walking animation in the right direction so it doesnt look like they're moonwalking side to side.
Alternatively, I might just not bother and add some kind of obscuring particle effect to hide the teleporting when units join or die
you can use the worldpositionstays option of setparent then use movetowards to gradually move the child to the new parent
Hi again!
I have this code here that I just to make rigidbodies follow each other (the first one in line is always a no collision enabled gameobject so it's never part of this issue). This is called in FixedUpdate
private void AddForceMove() {
var targetPos = _target.position;
var currentPos = _rb.position;
if (IsCloseToTarget(currentPos, targetPos)) {
// Debug.Log("Is Too Close!!");
// gameObject.GetComponent<Renderer>().material.color = Color.red;
return;
}
// gameObject.GetComponent<Renderer>().material.color = Color.green;
var direction = targetPos - currentPos;
var desiredVelocity = direction.normalized * _maxSpeed;
var currentVelocity = _rb.velocity;
var desiredVelocityChange = desiredVelocity - currentVelocity;
// The most we could change velocity given our max available thrust force.
var bestVelocityChange = Time.fixedDeltaTime / _rb.mass * _maxThrustForce * desiredVelocityChange.normalized;
var actualVelocityChange =
Vector3.ClampMagnitude(bestVelocityChange,
desiredVelocityChange.magnitude); // don't change more than needed
// rb.gameObject.name = "aVC=" + actualVelocityChange + " | cVN =" + currentVelocity.normalized;
_rb.AddForce(actualVelocityChange, ForceMode.VelocityChange);
}
My issue is that will sometime just bunch up and start blocking each other, any ideas of what i could do to make them recover better in that case?
OK interesting, so I would just put "worldpositionstays" in those parentheses, then where would I put "movetowards"?
'so I would just put "worldpositionstays" in those parentheses' - no - go read the docs
'then where would I put "movetowards"?' - Best would be a coroutine
So many vars...
yeah cause it's complicated it's more verbose
The solution to this issue depents on what you want to do when they block each other
complicated for me anyways
i guess the answers to that is whatever's the easiest to implement
It's complicated to read the code with every variable's type being var
i'm pretty bad with physics
oh sorry it just shows in my ide, true
i can fix this real quick
they are mostly all vector3s
I see, so perhaps you want to assign each axis of their positions to the random number between -1.000.000 and 1.000.000 once they've collided, is this right?
so you mean add a force in a random direction to try to resolve the blockage?
No, it was a joke. I said that I am not a prophet and have no idea how you want them to behave when the collision happens, that's why I tried to guess
I don't think that the previously suggested solution might work how you want
or maybe just increase trust force when this happens so they can push through
maybe a timer triggered by the first collision: if there's x collision in y amount of time trigger this response
Scripted Importer help needed
Please, consider not asking to ask, Cutie!
So you want to even worsen their fight?
hmm, maybe just the one at a time can do this, prioritizing the one following the leader
I mean, I don't know what's the purpose of your enemies fighting each other, but there should be something you expect them to do, right?
The other functionalities can be place in scripts on the objects themselves.
With a bit of refactoring, you could reduce the references to simply the game over object: https://gdl.space/osunuhiciy.cs
Perhaps consider making the game over object a child of the manager as it's necessary in every scene and for ease of referencing - the child object of this DDOL object will persist in every scene with it.
The others shouldn't really be managed by this object as they can simply access the manager for data and adjust themselves accordingly after the new scene loads:
Assuming Transition object isn't a persistent object, you'd simply reference the image component from the inspector and set it's size delta to the wanted value: https://gdl.space/galuxijujo.cs
With the main camera, you'd just update it's rect size https://gdl.space/xebilafomi.cs
And with the second player, camera, transition and whatnot you'd just have a script on them to destroy them if not multiplayer: https://gdl.space/emokerawas.cpp
Start would occur after the scene has loaded so these would all be completed after the scene has loaded.
best case this would just not happen, but making them move with physics (intended) can cause that i guess
the issue is mainly they stay blocked and it seems to get worst
so there needs to be a response (using physics)
Well, you move them in each others directions, so how to do you expect it not happen?
there's the 'IsCloseToTarget' method that generally makes them avoid accelerating if something happens to the one before them in line
I'm sorry, I didn't seem to get it
they are all following the next 'person' in line
if the person they are following slows down they will stop accelerating to hopefully avoid crashing
Alright, that's what you should have mentioned
You should perhaps clamp their speed then?
it is, maybe it's just a matter of setting those values better
See, their speed shouldn't be greater than that of the one they're following
good point, maybe i make sure that's the case aswell when they're too close, maybe they break or something
Yep
thanks, i'll experiment with that
Alright, wish you good luck ๐
You would need to explain. You said it is a custom format, but we need hard details to help
So setting worldpositionstays to true and then running delta3Trooper.transform.position = Vector3.MoveTowards(transform.position, new Vector3(0f, 0f, 0f), 0.3f);
Is just resulting in the units globbing in the center and not going to their assigned spots
I'm guessing the coords I give are referring to the highest parent and not the immediate parent, but I don't know how to chnage that
not really, you need to put that code into a loop inside a coroutine and I thought you wanted to move towards the new parent not 0,0,0
What details should I provide
I have the whole file format
Really simple
Just contains size of the image and the byte array of pixels to be loaded
also not sure where you get delta3Trooper from as it's delta2Trooper you are changing the parent of
There are 5 troopers all named like that, its interchangeable
then you should be using an array not unique names
I have an array for the parent slots and then a class to assign objects belonging to those slots to the numbered trooper names, that part is settled and working fine so unless I need to change it to make the objects follow MoveTowards its fine
This is my first project and I've been away a few months for school so I'm stumbling around and trying to get the reins again
it's not fine at all, you are going to end up with a shit ton of duplicate code
hmm.. I don't think this is going to work out because of all the removing and restarting, (even like removing the cameradivider, Transition2, MainCamera2 and Player 2)'
What do you mean?
The code shouldn't do anything different than what you had before
I said there's no cameraDivider, Transition2, MainCamera2 and Player 2 included in the script
Which script?
IN the PLayerManager script
You wouldn't need it, you'd place the multiplayer script on those objects.
They'd destroy themselves on Start rather than having the manager search for them
They wouldn't need a manager to manage them, they'd request the data from the manager and be able to manage themselves.
look, they all work perfecly fine with the transition yet I still gets an error there for no reason
It is never for no reason
Maybe show the errors
I tested something that when i press on player 2 button, there is no errors, but when i press on player 1 button, there's errors
You'll need to show the error
I'm trying to create an extension method for lists to simplify checking that they aren't empty a bit, but I get error cannot implicitly convert type 'method group' to 'bool'
What am I missing here?
//Desired function usage example
List<Vector3> someList = new();
if(someList.isEmpty)
{
//do stuff
}
public static bool isEmpty<T>(this List<T> a) where T : class
{
return a.Count == 0;
}
What's line 102 in the manager?
Code looks outdated and not what I shared
what?
There shouldn't be any Find or Get Component in any of the code I shared
Assuming you read and looked at this
Is the error line on the if statement?
It's an extension method so you ought to have the round braces () - parentheses.
Ah, so I can't extend new pseudovariables?
Are you referring to properties?
this is my script, and what I shown in the videos here that in the player 2 button there is no errors and everything is perfectly fine, but in player 1 button, there is an error but doesn't disturb me much. and when I say they work alright they work alright with everything, but for some reason not the transition1 image on line 102
in these videos
Um, probably?
This is the recent (a year old) discussion on it https://github.com/dotnet/csharplang/discussions/5811
also note that vec3 is not class
Ah, so it's not a thing in c# yet, but a possibility in the future?
I've already given you a suggestion for your original problem. #archived-code-general message
please, look at the videos i sent
right here
Before any of that, do what Dalphat said
it will only become red underline on playermanager
like this and in transition
When you see a red underline, hover over it and read what it says
Ok, so a very clear error
PlayerManager.instance
You didn't make a reference. You cannot use the type
Ah, it's a singleton. Yeah. I seem to remember Dalphat saying to use .instance earlier
If you are trying to do something someone said, follow ALL the directions
Tbf I'm guilty as it was written in the browser without any intellisense #archived-code-general message
Le gasp! For shame haha
Sorry about that then linedol. I misremembered
how can i make the gameover as a child while it's in the other scene?
Just drag the game over object as a child of the game manager in every scene
You'd just child the game over object to it - assuming you've got a game manager and game over object in every scene for testing purposes. They wouldn't really be necessary in every scene (but the first) when finalizing the build as the game is meant to transition in one direction - from beginning to end.
and where am i supposed to put the transition and cameraadjust script?
Probably on the objects you'd normally find to execute whatever code is written in them
You'll probably want to drag the necessary component references for each object too - it'd be the component on them.
They should be on the Transition1 object and main camera object, last I recall
More work for the level designer but fewer potential runtime errors
I'm assuming you know where to put the multiplayer script?
And the necessary editing (instance)
You'll need to configure this for each scene, if applicable - relative to objects available (for example, the second scene lacks the Transition1 so you won't need to put the script on that object)
it is barely working with the camera
Oh, I just realized that you did not want to modify the camera unless it was a single player adventure
Use that P2 if guard statement to not adjust your camera if it isn't single player
if(!PlayerManager.instance.P2)
{
//do stuff
}```
Same would apply with transition and whatnot
Hey everyone! I working on a small game where the player controls a mouse simulating computer. However, I am currently facing an issue with my virtual cursor where the mouse does not clamp at the game object position, causing the screen boundaries to not work and consequently drag other objects to the outside. How would one always keep the mouse position at the cursor?
How're you implementing it currently? Looks fair for the most part.
the saem thing for transition?
rather than using the mouse's position to change the position when dragging an object, use that fake cursor's position
I did thought about this solution which requires some work arounds and I thought there might be a better way
But I guess thats just what I need to
are you also wondering the extra stage button i placed over there next to the boss stage? it's more like an extra stage for the story telling of going to the next planet
Something you might want to look into https://discussions.unity.com/t/what-does-no-cloud-projectid-found-for-analytics-error-mean/253242
I have a custom editor that uses UXML and another, derived custom editor that uses the same base UXML. When add a field like [SerializeField] VisualTreeAsset inspectorXml in the base editor, then I have to set this field for each derived Editor script manually. Is there some better way to do it? I was previously just doing Resources.Load<VisualTreeAsset>("UI/some_editor") inside CreateInspectorGui but this seemed... wasteful...
huh?
They are referring to the error in your console
I am new to unity, I have a character made that has two movement types. I have the movement states as walking and sliding. Currently for testing I swap between the two using a hotkey, but obviously I'm going to have two terrain types. I'll have snow I can walk on, and ice I will slide on. What would be the best method for differentiating between the two? Check for the material my character is in contact with?
can I make everything louder?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerController : NetworkBehaviour {}```
why is this not working
I hae all the classes right?
no
make sure that your !IDE is configured so that you can use the quick actions to add the correct using directives
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
its not an IDE issue its this
i am aware. what i said is still how you can fix it
That wont fix it
if you configure your IDE you absolutely can use the quick actions to add the correct using directive
its not my IDE IDE has no colleration to this error
its a compiler errror
it is also a requirement to have a configured IDE in order to get code help here anyway. but yes, configuring it and using the quick actions will fix this
I just want to know do i have all the imports right?
why is the compiler not recongnizing this error?
am i missing a package
goto #๐ปโcode-beginner pls your not helping
It IS an IDE issue, if your ide was configureded correctly it would help to to fix the compiller error\
no it is not
Yes it will, itll tell you exactly how to fix it and even write the code for you
i already told you that you do not and that you can use the quick actions in a configured IDE to add the correct one
the IDE doenst have a built in Unity C# compiler
it is not my IDE
i jst want to make sure i have all the improts right
or if im missing packages
are you just incapable of reading?
Wow everyone tells you what's wrong but you refuse to believe
at no point were you told the issue is because of your IDE. you were informed that a configured IDE can fix this for you
it is not my IDE
no IDE has a built in C# compiler
i know exactly what the fucking issue is and exactly what namespace you need to add a using directive for. however if you would bother configuring your god damn tools you wouldn't need help with this
and you aren't worth providing help to
and again, a configured IDE would allow you to fix this with the quick actions. as has been stated multiple times
i missed a package
Well it is a rule to have a configured IDE. so with server rules, no one is allowed to help you!
Regardless of what misconceptions you apparantly have, a configured IDE is required in order to get help here
bro my IDE is not picking up on any errors
Exactly
that may have something to do with the fact that it is not configured
That is EXACTLY what they've been telling you
If you don't want to configure it, you must find somewhere else to get help
If ONLY someone had advised him to configure his IDE, what a shame
It's not picking up the error BECAUSE it's not configured.
Oh lag, you guys already wrote that
maybe if enough people tell them they'll eventually realize we were all right all along
quit spamming
https://docs.unity3d.com/ScriptReference/Random.html
Because the classes share the name Random, it can be easy to get a CS0104 "ambiguous reference" compiler error if the System and UnityEngine namespaces are both brought in via using. To disambiguate, either use an alias using Random = UnityEngine.Random;, fully-qualify the typename e.g. UnityEngine.Random.InitState(123);, or eliminate the using System and fully-qualify or alias types from that namespace instead.
same concept, but replace System with Unity.Mathematics in that description
but im wondering
what is the more supported version of it
if anyone knows how multuplayer works
that will compile
surely you bothered reading the docs to see that Netcode for GameObjects is unity's current networking solution
and this is #archived-code-general where you are expected to be able to read some documentation and have a basic understanding of how code works. as well as have a configured IDE
Have you read the #854851968446365696 yet?
There are some things you are required to do in order to get help here
ive been using unity for 2 years
so I was asking this yesterday but still haven't come to a satisfying answer. How can I sort all the item labels in the world similar to how Poe/diablo does it? using rigibodies and boxcolliders work alright, but fail when many objects are spawned. I've tried to resolve a location directly above the collision by using OnColliderEnter2D, but since all of the labels have the same function, when one moves up, the one it collided with does as well and they end up shooting up forever. any suggestions?
using rigibodies and boxcolliders work alright
your labels do not need physics. just use a physics query to find nearby ones
yeah i figured, but that is easier said then done
how would I use those physics queries to sort?
would I just BoxCastAll?
the physics query doesn't do any sorting. it just gets the nearby items or whatever as an Array/List
if two boxes are overlapping, the newest one would go above the older one
directly above
so would set the y position to the sum of the colliders extents
okay
Why did you jump channels and respond to something that wasn't for you?
so you give the objects some component that helps you determine what is newest and sort by that info to determine what is drawn on top
bruh why so serious i took a chance
lmoa
What?
That is meaningless. If you want help show what we neex
so should I keep a list of all of the labels and loop through it? also what if an object is sorted onto another? should I sort it all from newest to oldest? or vice versa, trying to logic it out in my head
i mean, the physics query would be used to find all of the nearby objects that need to display their labels. that would just keep giving you an updated list of them. then you just use that info to actually draw the labels sorted in the way you'd like. i'm not really familiar with the game you've referenced and you've not shown anything about your setup so i really can't be more specific than that, sorry
well the problem can be considered as a packing problem
in the image it sent, all of those labels are items on the ground
this is an image from my game, as you can see it current has the issue that I stated before where the labels go too high since they are constantly colliding with eachother as they move up
again, your labels do not need physics. they also don't really need colliders except for the possibly using the collider to determine how much space the label takes up
yes, i am just showing it since you wanted to see my current setup
it is a bad solution though
how do I make a message box?
In the editor or in the game?
or do you mean like a dialogue box?
idk, try googling native dialog or smth
looking sick btw!
thanks :D
I would look into "C# callbacks", one way you can do it is have a function that toggles your message box and an action that something can subscribe to, so it can respond when a "yes"/"no"/"cancel"/"ok"/etc button on the message box has been clicked
i did it with c# before but how do i run it with unity?
The same way you did it with C#, the only major difference would be how you choose to display it, for example, with a Canvas, or UIToolkit or another GUI tool
in C# I used messagebox.show(<string>); but it doesnt work in unity
Right, MessageBox is native to the System.Drawing namespace, which wont work in Unity, this is why they have a UnityEngine.UI for graphics, so you would have to create the actual visual of the message box yourself, either with a Canvas, UIToolkit or some other way of drawing UI, which also means youd have to create the callback that .Show would normally do for you
cant I do it so unity runs the c# program?
What do you mean "runs the c# program?" it can compile and execute your c# scripts, but im not sure what you mean by "program" in this context?
Technically yes, you can run programs with Application.OpenURL but I dont see how that might help with a message box inside Unity
i want the messagebox like as in windows notificatio
Right, and thats something you cannot use the native Windows API for (at least, not easily), in Unity that is something youd haeve to create yourself or maybe find a git project that already has done this, im not sure if theres any exe you can launch to create a message box for you, and even if you could, youd still need a way to know what button was pressed on the message box and have your code wait until one has been pressed
That, im not sure of, youd probably need some kind of dll or injector or something to listen for other applications, which sounds like a more involved approach to making a message box in Unity, unless your trying to make some native application outside of Unity?




