Unity Tutorial: Classes and How to Use Them

I’ve written a lot of Unity 3D blog posts. Yet, I have not yet written one about one of the fundamentals of object-oriented programming; classes. Today, I will remedy this problem with a quick introduction to classes in Unity. Let’s get started.

What is a Class?

Cars are often used as a metaphor to explain what a class is. In the real world, we can put just about every kind of car, motorcycle, or truck into a category called “vehicle”. Conceptually, we can define any vehicle to have specific components that we would expect them to have. For instance, an SUV, a trailer-truck, and a motorcycle all have wheels. However, an SUV has 4 wheels, a trailer-truck has 18 wheels, and a motorcycle (usually) has 2 wheels. So, even though each vehicle may have a different number of wheels, we can define them as all having some number of wheels. Likewise, just about every vehicle has a model name and a year of production. Even though the SUV, trailer-truck, and motorcycle all have different model names and years of production, they still have both of these components. Additionally, every vehicle has a top speed and a horsepower that their engines produce.

In programming, classes provide an easy way to create objects that all have the same components but unique values for those components. Additionally, classes are not limited to just variables. A vehicle also has the ability to accelerate, for instance. In our program, we could have an Accelerate() function for each vehicle. To try and explain this concept graphically, here’s my poor attempt at an information tree (Disclaimer: I know almost nothing about cars):

Why Classes are Useful in Programming Unity

Consider if we had a game where we had a Vehicle class and we create a motorcycle and an SUV object, which are both “Vehicles”. We could create separate values for each object and wind up with two very different objects in our game. Beyond these basic variables I have discussed, we could take it further and say that each vehicle has a Mesh and MeshRenderer variable, which would allow us to give each vehicle a unique 3D model with unique textures.

Another good example of classes would be creating enemies in a game. You could make an “Enemy” class that would contain variables like hitpoints, damage, armor, speed, Attack(), Defend(), and Move(). Any enemy you create can have these variables custom tailored to your liking. You may want an enemy with high hp and high damage but low armor? Not a problem. Maybe you want another enemy that is incredibly fast with low damage, low armor, and moderate hit points. You can do that too. At the end of the day, all of these enemies, even though they have unique values, are still an object of the “Enemy” type. There’s a seemingly endless number of unique enemies you could create using this class.

I want to stress the point that my explanation of classes is incredibly primitive. Classes are a cornerstone of modern day programming languages and game development. I highly recommend reading into them further if you’re interested in programming.

How to Use a Class in Unity

In this post, I will be using C# since it is my preferred language in Unity. Each language that implements classes has its own syntax for declaring and using classes. In C#, you would create a class like this:

class Vehicle

{

int tires, year, hp, topSpeed;

string model;

void Accelerate()

{

Move(Vector3.forward * hp); //not real code

}

}

Once you have the class created, you can create a new object of this class like this:

Vehicle SUV = new Vehicle();

You can then access the “members” of that object like this:

SUV.tires = 4; //SUV has 4 tires

SUV.year = 2010; //SUV was made in 2010

SUV.hp = 160; //SUV has 160 hp

SUV.topSpeed = 120; //SUV has 120 topSpeed

SUV.model = "Yukon"; //SUV is a "Yukon"

SUV.Accelerate(); //SUV will Accelerate

Typing all of that stuff out is redundant and time-consuming. Fortunately, classes have these things called “constructors”, which can be used to initialize a new object of the class with the variables you want. A class with a constructor looks like this:

class Vehicle

{

int tires, year, hp, topSpeed;

string model;

Vehicle(int _tires, int_year, int _hp, int _topSpeed, string _model)

{

//this is a constructor for the class. When a new Vehicle is created,

//you can use this constructor to execute the following code

tires = _tires;

year = _year;

hp = _hp;

topSpeed = _topSpeed;

model = _model;

}

void Accelerate()

{

Move(Vector3.forward * hp); //not real code

}

}

Now I can create a new Vehicle object and initialize these values quickly:

Vehicle motorcycle = new Vehicle(2, 2000, 65, 100, "vstrom");

The motorcycle has 2 tires, the year 2000, 65 hp, 100 topSpeed, and a model of “vstrom”.

Let’s Make Something

Now we’ll apply this to Unity. We’ll create a scene and use classes to output information to our console about the objects we create. This will be an incredibly simple program but it will help illustrate how to use classes. We’ll create an enemy class and have a script that will detect button inputs and modify the class variables of specific objects.

First of all, create a new project in Unity with whatever settings you want.

Create a new C# script in your project and name it “Enemy”

Open up the Enemy script and copy the following code into it:using UnityEngine;using System.Collections;public class Enemy{ public int hitpoints, damage; string name; public Enemy(int hp, int dmg, string ID) { //this constructor assigns hitpoints, damage, and name to the //values passed into the constructor hitpoints = hp; damage = dmg;

Now you need to create a new Game Object in the scene and attach the PlayerInput script to the new game object.

At this point, if you play the game, you should notice console messages when you press SPACE, Left Control, Left Shift, or Left Alt. Each key does something different. Each one will decrement somebody’s HP and the console will let you know what the remaining HP is.

Conclusion

Overall, this is the very basics of classes in C#. Again, I highly recommend reading into classes further. They are incredibly powerful and important in programming and game development in general. My hope is that this post has helped those of you who are unfamiliar or new to programming to better understand classes and see how they can be useful. I hope to make some more blogs about classes and more of their functionality in the future.