Custom Classes!

addam davis
3 min readJul 22, 2021

Objective: Define custom classes and implement them into your program!

What is a custom class? Custom classes are classes that do not inherit MonoBehavior.

For this example, we want to create something that is modular and standalone that defines something, let’s say “weapon stats.” If you have multiple weapons, it doesn’t make since to define in the player’s class because the stats aren’t related to the player, it is related to the weapons.

we are going to ornate a custom class that defines weapons. Within the weapons class we are defining what the name is, the fire rate, and the ammo count.

In C# we have the option to create classes within classes, so we don’t have to create a new C# class is we don’t want to. To create a new class, we simply aim above the main class in the script. If you are in the player’s script, then you place the custom script above the player class. You will need to follow the same syntax.

This class will not inherit MonoBehavior. It will be an object class that is basically going to be defined how we want it to be. Think of a custom class as a blueprint, what we are doing is filling out said blueprint. What makes up the blueprint for these weapon stats? The name, fire rate, and ammo count.

You can now start defining what our weapon stats object is going to be.

What this has done is define weapons stats as a class. To make use of the class we need to create that object which is weapon stats. In the Void Start Method we can create variables that will hold what type of weapon it is.

Now you could hard code in specific stats.

However, it is best to always avoid hard coding and use variables or parameters. In this tutorial we are going to use parameters on the constructer. What is a constructer?

A constructer is one of the benefits to using custom classes. A constructer is how we can initialize things. The example code above in the void start method is initializing objects. We can do this in Void Start because it is a MonoBehavior and internally unity will call this for us.

The constructer going inside the custom class and is named the same as the class.

This is creating a modular program where nothing is hard coded in and defined as you the user is going to define what a weapon stat is. We can now initialize the weapon stat variable.

That’s how you initialize the blasters. You can always add more weapons and their stat information. You could take these stats and attach them to a UI element and display them. We’ve covered this in a tutorial before if you need a refresher on how. As always, don’t be afraid to experiment with your code, and I’ll see you in the next tutorial.