Unity C# Basics — Classes: MonoBehavior

Introduction

In this article, we will talk about what Classes with MonoBehaviour

Classes are needed for Object Oriented Programming or OOP. OOP is programming that revolves around “objects” containing fields (attributes/variables) and procedures ( methods). Classes will define and established the attributes and methods that each object(s) of that class will inherent.

MonoBehaviour

MonoBehaviour allows for the attachment of scripts to Game Objects in Unity. Below is the Player Game Object with the Player Script.

In the Player script, the attributes of speed, firepos and laserPrefab are declared at the top of the script. In the Update, you have two methods, CalculateMove() and Shoot(), that handle the movement and shooting behavior. The Shooting Method just handles creating the Laser Prefab. The Laser is its own Game Object with its own behavior.

Each Laser Prefab, has the Laser script and is the Laser Class.

The attribute in the Laser Class is the speed and it has a Method of Movement(), which handles its movement behavior.

You can see how the Player game object has a script of the Player Class that handles all of the behavior of the player like moving left to right. There is also the Laser Prefab game object that has a script of Laser Class that handles its behavior of moving up the screen.

Conclusion

Classes define the individual behavior of game object(s), so each of the game’s functionality is modular to that object and helps keep the code clean and easy to debug.