Must create new Vector2 to assign to a Vector2 array?

Hello all,

I’ve got a Vector2 array that I built in C# like so:

public Vector2[] vecArray;
vecArray = new Vector2[]
{
   new Vector2( 0, 0 ),
   new Vector2( 0, 0 ),
};

Now I’m able to assign values to it like this:

vecArray[0] = new Vector2( 1, 1 );

However I’d like to be able to assign to it without creating a new Vector2 each time. Something like:

vecArray[0] = Vector2( 1, 1 );

This line of course isn’t valid, but is there some way to do this? I’m trying to avoid making garbage. If this were another array type (like int) I could assign directly to it or make a var outside that I reuse instead of making a new one each time. Does this seem reasonable or am I missing something here? :slight_smile:

Thanks for any input,
-d

vecArray[0].x = 5;
vecArray[0].y = 9000;

(also note, when you “directly assign” an int to it, you’re still making a new int)

Thanks for the quick response. So you’re saying no matter how a value gets assigned to it, a new var is being made? So if this were being done a lot, like every frame, garbage collection would kick in more often?

Cheers,
-d

Vectors, ints, floats are all structs which have the benefit that they are created/destroyed very efficiently. Don’t worry about it. Just focus on making stable, maintainable code, then worry about benchmarking/optimizing later.

1 Like