I recently came across a thread where someone said that creating Vectors on your Update function causes Unity’s Garbage Collection to mess up ( can’t find the thread anymore).
Is this true? Is saying new Vector3(0,0,0) on Update bad practise?
Every time you use “new” for anything you allocate memory, even if it’s temporary. Because of this, is a good idea to avoid “new” inside of the update function since it’s called on every frame. Instead, if you need to use a vector inside of the update function it’s more efficient to use a field variable that you can reuse on every frame.
You might want to create the vector in your awake or start method and re use in your update, since you will allocate memory every time you use new, and discard the old vector object which will create a lot of garbage for the GC.
All of you guys are forgetting that Vector3 is a struct and value types are only GC’d if they are fields of a reference type (or if you make a struct containing reference types - which you shouldn’t do).
Doing that every frame should just deallocate the memory on the stack when it goes out of scope and if you do what others are telling you by making it a variable in your class you’re actually opening up the potential for additional GC if and when that class instance is destroyed.
The long and short of it is - this is fine to do and you should be worrying about other things in your project
I think you are right because I came with some wonder as Unity was adding a new vector3 +transform.position in their Unity Official Project and if it is stack and it will auto adjust memory for unused data blocks so I believe it will not make a problem. Thank You