Unity Basics Course: Creating Classes

Unity is a powerful engine for game development that uses the C# language to create games. C# supports Object-Oriented Programming (OOP), which helps programmers write code efficiently and in a reusable manner. This article will explain how to create classes in Unity in detail.

1. Understanding C# and Object-Oriented Programming

A class is the fundamental unit of object-oriented programming, defining data and the functions that process that data together. In C#, the following basic concepts exist:

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.
  • Property: Data defined in the class.
  • Method: A function defined in the class.
  • Constructor: A special method that is called when an instance of a class is created.

2. Creating a Unity Project

Before starting to write a class in Unity, you must first create a Unity project. Create a new project in Unity Hub and select the basic 3D template. Once the project is loaded, follow the steps below.

3. Creating a Class

Right-click in the project’s Assets folder and select Create > C# Script to create a new script. Name the script MyFirstClass. Double click on the script to open it in Visual Studio or your preferred code editor.


    using UnityEngine;

    public class MyFirstClass
    {
        // Properties
        public int health;
        public string playerName;

        // Constructor
        public MyFirstClass(string name, int initialHealth)
        {
            playerName = name;
            health = initialHealth;
        }

        // Method
        public void TakeDamage(int damage)
        {
            health -= damage;
            if (health < 0)
                health = 0;

            Debug.Log(playerName + "'s remaining health: " + health);
        }
    }
    

3.1. Class Explanation

In the above code, MyFirstClass is used to manage the player's health and name. The properties are health and playerName, which are initialized through the constructor when creating an instance. The TakeDamage method reduces health when damage is taken and logs the result.

4. Using the Class

To use a class in Unity, you need to create an instance in another script. Let's create an instance of the MyFirstClass class:


    using UnityEngine;

    public class GameManager : MonoBehaviour
    {
        void Start()
        {
            MyFirstClass player = new MyFirstClass("Player1", 100);
            player.TakeDamage(20);
        }
    }
    

4.1. GameManager Class Explanation

GameManager class is a script that inherits from Unity's MonoBehaviour. The Start method is called when the script starts, and here we create an instance of MyFirstClass and call the TakeDamage method to reduce health.

5. Working with the Unity Editor

Now, return to the Unity Editor and add the GameManager script to an empty game object. Create an empty game object and drag the GameManager script onto it. Now, press the play button to check if the player's health is logged correctly.

6. Expanding the Class

Let's expand the class by adding various functionalities. For example, let's add a Heal method so the player can recover health:


    public void Heal(int amount)
    {
        health += amount;
        if (health > 100) // Maximum health is capped at 100
            health = 100;

        Debug.Log(playerName + "'s current health: " + health);
    }
    

6.1. Using the Heal Method

To use the Heal method, we will call it from the GameManager class:


    player.Heal(30);
    

7. Understanding Classes and Inheritance

Inheritance is one of the important concepts in object-oriented programming. You can inherit a class and add new functionalities. For example, let's create a Warrior class that inherits from MyFirstClass:


    public class Warrior : MyFirstClass
    {
        public int attackPower;

        public Warrior(string name, int initialHealth, int initialAttackPower) : base(name, initialHealth)
        {
            attackPower = initialAttackPower;
        }

        public void Attack()
        {
            Debug.Log(playerName + " deals " + attackPower + " damage!");
        }
    }
    

7.1. Using the Warrior Class

Let's create an instance of the Warrior class and call the attack method:


    Warrior warrior = new Warrior("Warrior", 120, 50);
    warrior.Attack();
    

8. Utilizing Classes

The ways to utilize classes in Unity are limitless. For example, enemy characters, weapons, items, etc. can be created as classes, each defining their own properties and methods to express various behaviors.

9. Conclusion

In this tutorial, we explored how to create classes in Unity and the basic principles of object-oriented programming in C#. By utilizing classes, you can write more structured and maintainable code. Continue to understand various classes and inheritance, and enhance your skills when creating games.

10. References