For my grid-system (2D-array) I'm creating a Index2
-struct. Which is very similar to a Vector2
.
Running into some issues I read up on structs. Coming across the mutable and immutable subjects.
Long story short, mutable structs are bad. So then I wondered, how would I make my struct immutable? Which led me to this post.
If understood correctly, to make a struct immutable you have to make sure once the instance is created, the members of the instance cannot be modified.
But then when I look at the Vector2
-struct in unity. Once you have created a new Vector2(0f, 0f)
, you cán modify its values:
Vector2 myVector = new Vector2(1f, 1f);
myVector.x = 2f;
This works just fine.
Same with the .Set
-method:
Vector2 myVector = new Vector2(1f, 1f);
myVector.Set(2f, 2f);
Also looking at the definition of a Vector
, I dont see any of the solutions suggested in the above linked post.
Which makes me wonder a couple of things?
- Is a
Vector2
an immutable struct? - If it is, how is it structured to be still immutable while being able to modify members?
- If it is not, why is it still a safe struct to use?