This is one of those “I have been doing it for years but I don’t know why” questions. It is about the new keyword in c sharp, for example when changing the position of an GameObject, why do we have to say
gameObject.transform.position = new Vector3(xPos, yPos, zPos);
how does this not create memory leaks or is this where managed code kicks in? Surely this can’t mean that for each update a new instance is created of Vector3???
Sorry for the noob question, but I’m a self taught programmer - any explanation will help, thanks
A new instance of a struct is created each time you call new. If it is done in a function, it will be allocated on the stack and go out of scope and be automatically cleaned up when the function exits. Allocating a new object, especially a struct, and especially a simple struct like a Vector3, is a reasonably fast operation. Because a user-defined struct is a value type it costs no more** in terms of pure allocation, than declaring an int or float.