In C# there’s no way to modify a component of a vector. If I want my character to experiment a certain horizontal and vertical force, but zero in the z component, I can’t just do it as in JavaScript:
currentforce.x = X;
currentforce.y = Y;
//don't need to do anything with z because it's zero
Instead, I’m forced to create a NEW vector everytime I want to update mine (and it happens on each frame):
currentforce = new Vector3 (X, Y, 0);
I’ve always been told that creating and destroying objects is costly, and I’m currently facing serious optimization issues. Is this ‘new’ different? could I do the same thing in a different way?
When people talk about object creation being expensive in Unity, they’re referring to calls to Instantiate, Destroy, etc, not object construction in code.
What stringbot said, as well Vector3 is a struct (value-type) and not a class, so it does not generate garbage, cannot be null (unless wrapped in a nullable type), and passes by copy by default rather than by reference. It also doesn’t have a true constructor and new Vector3(x, y, z); just modifies all 3 values as one call rather than calling them 1 at a time.
Structs are considered, for the most part, value types in .NET, so in a local function, will be created on the stack so the operation is reasonably cheap. As Ntero said, the two pieces of code example they gave are equivalent, it’s just that JavaScript/UnityScript is hiding the dirty work for you in the declaration. Unless you are on a seriously restricted mobile platform creating a new struct is very cheap.
Edit: Meh, should have read the entire thread before posting. End of day, very tired. Ntero already said it clearly enough.