C# : Custom Classes and Constructors

Matteo Lo Piccolo
3 min readMay 3, 2021

--

In the previous article we had see how instantiate the classes.
Now we see what is a Custom Classes, Constructors, and how they work.
I won’t go into much depth with this topic for now, but some things I think are important enough, at least to know.

We create again Person class or delete the variables, as you like

Every time we create script in Unity they will always DERIVE from MONOBEHAVIOUR.

To create a CUSTOM class, we simply DELETE the word MONOBEHAVIOUR and the COLON

Now, is important understand this: CUSTOM classes cannot be attached to an object. Never. ONLY scripts derived from MONOBEHAVIOUR can.
The start and Update methods don’t work, so we can delete them.

Custom Class Person

Now, the syntax of Constructor is this

It seems a method, with some little difference : the name is the same of the Class, no VOID or RETURN TYPE, parentheses at the end and open / close curly brackets.

This is an EMPTY CONSTRUCTOR, and it has no PARAMETERS.

Normally, we use Constructors to INITIALIZE THE FIELDS.
Here we have a constructor with parameters

Constructor with PARAMETERS

The keyword “THIS” refers to the current object.
And we have two fields very similar :
string Name and the parameter name.

The uppercase refers to the Class, while the lowercase is refers to the parameter we pass.

When we instantiate the Custom class and we have a Constructor with Parameters, we can do it with the “new” keyword and PASS THE PARAMETER OR PARAMETERS DIRECTLY at the moment of instantiation

Pass string parameter directly at the moment of instatiation

Application C # and Unity sometimes don’t have the same execution logic, but the concepts behind it are the same, and knowing that these situations exist can be really helpful.

I preferred to mention now, but these are concepts we will return to later. From the next article we will start with our project!

--

--

Matteo Lo Piccolo
Matteo Lo Piccolo

Written by Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!

No responses yet