What are Constructors

C# Concepts | Classes

Jordan T Kay
Nerd For Tech
3 min readJan 31, 2023

--

Objective:
Optimize weaponDatabase through the use of constructors

SETTING THE SCENE

We are continuing our WeaponDatabase project that we created in our previous article. In this project, we created two scripts…

  1. One script contained our custom class Weapon
  2. The other contained our WeaponDatabase script used to instantiate and store our weapons

Custom Class ‘Weapon’

WeaponDatabase Script

Now, this system works. But it is a headache. We needed to use 45 lines of code JUST to create 4 weapons. Imagine if we have 50 weapons we needed to create. Imagine if we had more fields needed to be filled in. There has got to be an easier way…

CONSTRUCTORS

Constructors is a concept used to initialize items within a single line of code.

A constructor is placed within a custom class and is named the exact same thing as the custom class.

Declaring A Constructor

To declare a constructor, we need to jump into our custom class…

To declare a constructor, we need to use the keyword Public and name the constructor the same thing as our custom class. By making our constructor public, we are allowing outside scripts access to this constructor.

We then need to pass in the parameters needed (these parameters are our fields). Within the constructor, we then need to associate the parameters to our classes fields.

NOTE:
“this.” is an extra precaution to better outline that we are taking our custom class’ variables and having them equal to our parameters. This is best practice because our variables and parameters are named the same thing.

Initialization With A Constructor

To initialize our newly declared constructor, we need to jump into our WeaponDatabase script.

With our constructor in place, now to create a new weapon all we need to do is initialize our weapon variable and pass in the parameters needed. Infact, we now have a nifty tooltip to tell us what parameters our constructor needs!

So, lets take our 45 lined script and optimize it with our constructor!

As shown, we have taken our 45 lined script and made it into an 18 lined script!

MULTIPLE CONSTRUCTORS

A single custom class can have multiple constructors. This will allow us to have an…

  • empty constructor (so we can initialize the variables we choose to)
  • a constructor with all the parameters
  • a constructor with selected parameters to make a custom item

The constructors I created are…

  • an Empty Constructor
  • A constructor with all the parameters
  • A constructor that has every parameter BUT our description (not every weapon will need a description)

Now, when we attempt to instantiate our new weapons we have different tooltips that represent all of our constructors.

--

--

Jordan T Kay
Nerd For Tech

Join my journey into game development with Unity. Learning all I can to produce quality games. 🚀