Constructors

Constructors are a special type of method which can be used to define how instances of a particular class or struct are created and to initialize their starting values. A constructor has no return type and its name matches the declaring type like so:

public class Person
{
   public readonly string FirstName;
   public readonly string LastName;
   
   public Person(string firstName, string lastName)
   {
      FirstName = firstName;
      LastName = lastName;
   }
}

// In some other method:
var person = new Person();// Error: Person does not have a parameterless constructor.
var john = new Person("John", "Smith");

If you do not define any constructors in a type, the compiler will automatically give it a default parameterless constructor.

Constructors cannot be used in classes that Inherit from MonoBehaviour because they need to be added to a specific GameObject using its AddComponent method. Technically, you can use a parameterless constructor but it will not be able to do much because it will be executed before Unity gives the component its reference to the GameObject or any of its Serialized Field data, so you will generally want to use the Awake message instead.

Readonly Fields

Fields with the readonly keyword can only be assigned in a Constructor or Field Initializer:

// Using the above Person class.
var john = new Person("John", "Smith");
if (john.FirstName == "John")// We can get the value because it is a public field.
{
    john.FirstName = "Jim";// But this gives a compiler error because it is a readonly field.
}

// But we could always make a new Person with the name we want:
var jim = new Person("Jim", john.LastName);