I'm a beginner to both Unity and C# but I was looking through the Unity code and I noticed that Vector3 was a struct type in Unity.
However, I was wondering why is it that I can then declare something like this:
transform.position = new Vector3();
And then also have it default to a position of (0,0,0). Isn't it the case that in C# a struct can't have a parameterless constructor? Going into Vector3.cs I also can't see anywhere that the default constructor Vector3() was initialized. I can only see two constructors, one for 3 parameters and one for 2 parameters.
Anyway, I guess my questions are:
A struct
in C# can (since a few versions ago) have a parameterless constructor, but even if it does not, constructing it results in it being default-initialized, i.e. new Vector3()
is the same as default(Vector3)
. That does not have to be declared anywhere, that is how value types work in general ‒ a default value is always valid and results in all zeroes.