Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 698
reetyn Avatar asked Dec 22 '25 06:12

reetyn


1 Answers

struct has always implicit parameterless constructor, as per the documentation:

Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct implicitly has a parameterless instance constructor, which always returns the value that results from setting all value type fields to their default value and all reference type fields to null (§8.3.3). A struct can declare instance constructors having parameters.

like image 52
Michał Turczyn Avatar answered Dec 23 '25 19:12

Michał Turczyn