Search code examples
c#.netunity-game-engine

How come you can use a Vector3 constructor without parameters in Unity when it's a struct?


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:

  1. How is Unity using a parameterless Vector3 constructor when it's using C# and .NET?
  2. Where is the Vector3() constructor initialized to default to returning a position of (0,0,0) since I can't see a default constructor in the Vector3.cs file?

Solution

  • 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.