When it comes to developing games with Unity, understanding the basics of C# scripting is essential. Unity uses C# as its primary programming language, which allows developers to create interactive, dynamic, and complex game mechanics. One of the foundational concepts in C# is the use of classes and objects, which are integral to organizing and managing code effectively.

At its core, C# is an object-oriented programming language. This means that the language is designed around the concept of objects, which are instances of classes. A class can be thought of as a blueprint for creating objects. It defines the properties (attributes) and methods (functions) that the objects created from the class will have. This paradigm is particularly useful in game development, where different game elements can be represented as objects with specific behaviors and characteristics.

Understanding Classes

A class in C# is defined using the class keyword followed by the class name. The class name should be descriptive of what the class represents. For example, if you are creating a game about cars, you might have a class called Car. Inside the class, you define variables and methods that describe the car's attributes and behaviors.

public class Car
{
    // Properties of the car
    public string color;
    public int speed;
    public string model;

    // Method to describe the car's behavior
    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, the Car class has three properties: color, speed, and model. It also has a method called Drive that outputs a message to the console. These properties and methods define the characteristics and actions that an instance of the Car class (an object) can have.

Creating Objects

Once a class is defined, you can create objects from it. Creating an object is known as instantiation, and it involves using the new keyword followed by the class name and parentheses. This process allocates memory for the object and returns a reference to it.

Car myCar = new Car();
myCar.color = "Red";
myCar.speed = 100;
myCar.model = "Sedan";
myCar.Drive();

In this example, myCar is an instance of the Car class. We set its properties to specific values and then call its Drive method. Each object can have different property values, allowing for a wide variety of behaviors and characteristics in your game.

Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming. It involves bundling the data (properties) and methods that operate on the data into a single unit or class, and restricting access to some of the object's components. This is typically achieved using access modifiers such as public, private, and protected.

By default, class members are private, meaning they cannot be accessed from outside the class. However, you can use the public keyword to make them accessible from other classes. Encapsulation helps protect the integrity of the data by preventing unauthorized access and modification.

public class Car
{
    // Private fields
    private string color;
    private int speed;
    private string model;

    // Public methods to access private fields
    public void SetColor(string carColor)
    {
        color = carColor;
    }

    public string GetColor()
    {
        return color;
    }

    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, the color, speed, and model fields are private, meaning they cannot be accessed directly from outside the Car class. Instead, we provide public methods SetColor and GetColor to modify and retrieve the color field. This practice ensures that the internal state of the object is not directly exposed, allowing for better control and maintenance of the code.

Inheritance

Inheritance is another key concept in object-oriented programming that allows a class to inherit properties and methods from another class. This promotes code reuse and establishes a hierarchical relationship between classes. The class that inherits is called the derived class, and the class being inherited from is called the base class.

public class Vehicle
{
    public int speed;

    public void Move()
    {
        Console.WriteLine("The vehicle is moving.");
    }
}

public class Car : Vehicle
{
    public string model;

    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, the Car class inherits from the Vehicle class. This means that Car automatically has access to the speed property and the Move method defined in Vehicle. The Car class can also have its own unique properties and methods, such as model and Drive.

Polymorphism

Polymorphism allows methods to do different things based on the object it is acting upon, even though they share the same name. This is achieved through method overriding and interfaces. Method overriding occurs when a derived class provides a specific implementation for a method that is already defined in its base class.

public class Vehicle
{
    public virtual void Move()
    {
        Console.WriteLine("The vehicle is moving.");
    }
}

public class Car : Vehicle
{
    public override void Move()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, the Move method in the Car class overrides the Move method in the Vehicle class. When Move is called on a Car object, the overridden method in Car is executed, demonstrating polymorphic behavior.

Interfaces

Interfaces define a contract that classes can implement. They specify what methods a class must have, without dictating how those methods should be implemented. Interfaces are useful for defining capabilities that can be shared across different classes.

public interface IDrivable
{
    void Drive();
}

public class Car : IDrivable
{
    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, the IDrivable interface defines a Drive method. The Car class implements this interface, providing its own implementation of the Drive method. This allows different classes to be treated as IDrivable objects, enabling polymorphism and flexibility in code design.

Conclusion

Understanding classes and objects is fundamental to scripting in Unity with C#. By mastering these concepts, you'll be able to create organized, efficient, and scalable game code. Classes and objects allow you to model real-world entities in your game, encapsulate data and behaviors, and reuse code through inheritance and polymorphism. As you continue to develop your skills, you'll find that these principles are crucial for creating sophisticated and engaging games across multiple platforms with Unity.

Now answer the exercise about the content:

What is the primary programming language used in Unity for game development?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Unity scripting with C# - Basics: Understanding inheritance and polymorphism

Next page of the Free Ebook:

14Unity scripting with C# - Basics: Understanding inheritance and polymorphism

6 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text