What are classes in Unity
Classes are a crucial component for object orientated programming, or OOP. The premise is that you can create clean, organized programs. It allows you to break functionality into separate classes and have methods for each individual feature. The reason we would use this is because it is easier to debug and maintain.
Let’s take a quick look at an example of how you can create a couple methods of creating the code for something, and why doing it through a more streamlined class method is easier. First, we can create a new public class above our monobehavoiur:
As we can see, we have our weapons name, attack speed and damage as the variables for these weapons. Next, we can call each individual weapon in our Monobehaviour and then enter in all the information within our void start. However, if we wanted to add another 10 weapon types, this would be a long and tedious process that can be simplified. One such method is we can create a constructor within our new class:
As we can see with this above example, we took the 4 lines of code for each we needed to type to define each weapons stats into just 1 line for each individual item.
Here, we have a 3 different methods of creating the stats of our item with a new Items script and creating the new items in our database. Now, if we wanted to create an array to work with, we could simply do this:
In order for us to be able to do view this in our Unity Editor, we need to be sure to go back into our Items class and create a [System.Serializable] line of code to have it work, as well as be sure that we get rid of the Mono Behavior in the class:
From here, we can go into our Unity Editor and create how many items we want and adjust them from there, giving game designers the ability to make changes on the fly if you are just there to set up the programming:
If we fill it out from here, the name will change once we adjust it in the editor:
Now, let’s take a quick look at how we can build an item system through class inheritances. First, let’s set up our Items script to have our generic information that we want all of the items to work with:
Next, let’s add in a script for armor and weapons and with those, give them class specific attributes that we want them to have based on their item type:
Finally, let’s go into our database script and add in some armour and weapons to work with, and assign them the proper class as we enter them, along with making sure that all 3 prior scripts have [System.Serializable] so that we can see the attributes in the editor:
Finally, let’s take a look at our editor and see how the armour and weapon will share the same base attributes, but then have class specific ones:
As we can see, the armor and the weapon class specific items have their own respective attributes along with the 3 basic shared attributes.
Now that we’ve had a basic look at classes, we can see how to further implement them in the future to our game.