What does { get; set; } in Unity mean?

by Liam Cubicle Published February 22, 2024

Getters and Setters in Unity

The getter and setter properties are great tools for creating classes in Unity, especially manager classes. They are used to control access to private variables within classes. They are mostly used with MonoBehaviour scripts.

In this article, you will learn how to use the getter and setter properties in Unity.

📄 Resources:

What is Get property?

The Get property is used to set the place to return the value of a private variable. It gives access to other parts of your code to access the private variable without modifying it. That is, read only.

Here’s an example of how you would declare a public get method on a Property:

public int Health
{
    get
    {
        return 5;
    }
}

In this example, the Health property will always return a value of 5. Later on, I will show you how to return the value of a backing variable. The best trick is that you can actually modify the value of the backing variable before you return it. This enables you to sanitize or reformat data to the consumer. We’ll cover that, too.

What is Set property?

The Set property is used to give access to modify the value of a private variable. It allows access to other parts of your code to change a private variable.

Here’s an example of how you would declare a public set method on a Property:

private int _health;

public int Health
{
    set
    {
        _health = value;
    }
}

Note that we used a special variable in the set method, value. The value variable represents the input that you provide on the right hand side of your set. For example, suppose you wanted to set _health to 5.

private void SetHealthTo5()
{
    Health = 5;    
}

If you run this method, the value of value in the set method is implicitly set to 5. It is as if you wrote the following:

In this example, the Health property will always be set to the value that you provide. But, you can use the set method to modify or sanitize the input before applying it to the backing variable. This enables you to have more powerful properties in your code that are more reliable and safer to use.

Using only the Get property makes your private variable read-only, but combining it with the Set property grants other parts of your code to modify the private variable.

📄 Resources:

How to use Get and Set properties in Unity

{ get; set;}

To use the getter and setter properties in Unity, you need to declare a private variable first. Let’s declare a private integer, _health. We want to control access to the variable, so we will make it private. Later on, we will open up access with a public Property with get and set methods. But first, let’s create that private health integer. Here’s how you would declare the private variable:

public class PlayerController : MonoBehaviour
{
    private int _health;
}

Now that you have created a private variable, you can create a public Property. This property will expose the backing variable, health, using the get{} method. Here’s an example of how you could create the property and use the get{} method to return the health variable.

public class PlayerController : MonoBehaviour
{
    private int _health;
    public int Health
    {
        get
        {
            return _health
        }
    }
}

In the example script above, the Get property is used to return the value of the private variable health. Now, the variable is read-only, to change that, a Set property needs to be added.

To create a setter property with the health variable:

public class PlayerController : MonoBehaviour
{
    private int _health;
    public int Health
    {
        get
        {
            return _health
        }
        set
        {
            _health = value;
        }
    }
}

In the example script above, the setter property is used to give access to modify the private variable.

Protect your variables with the Set method in Unity

The most powerful feature of the set method is that you can inject additional logic and validation in your Set method. This logic runs before you write the value to the backing variable. As a result, you can control, sanitize, and protect your backing variable from unsafe operations. In the example below, we want to make sure that the health value is never a negative value. To do that, we use a conditional check in our Set method. In the Set method, we evaluate if the input value is greater than or equal to 0. If it is, then we apply it to the backing variable. If the input value is less than 0, then we log out an error.

This approach helps you to protect your variables from unsafe or incorrect input. Even when you’re working on an incredibly small project, using this technique can protect your game from bugs or unexpected errors in the data.

public class PlayerController : MonoBehaviour
{
    private int _health;
    public int Health
    {
        get
        {
            return _health
        }
        set
        {
            if (value >= 0)
            {
                _health = value;
            }
            else
            {
                Debug.LogError(“Health value cannot be negative!”)
            }
        }
    }
}

How to use the get methods from another script in Unity

Now, that you know how to add the getter and setter property to a private variable, how do you use it?

Let’s say you want to display the health variable in another script. In this example, let’s suppose we want to write the player’s current health to the console. To do this:

  • Get a reference to the PlayerController component.
  • Access the player.Health getter property.
  • Log the current health to the console.
public class HealthDisplay : MonoBehaviour
{
    public PlayerController player
    void Update()
    {
        int currentHealth = player.Health;
        Debug.Log(currentHealth);
    }
}

📄 Resources:

How to use the set method from another script in Unity

Let’s say you want to display the health variable in another script. In this example, let’s suppose we want to set the player’s current health to 50. To do this:

  • Get a reference to the PlayerController component.
  • Assign a value to the player.Health setter property.
public class HealthModify : MonoBehaviour
{
    public PlayerController player
    void Start()
    {
        player.Health = 50;
    }
}

The health has been modified to another value.

Conclusion

Now, you have learned how to use the getter and setter properties in Unity. The properties are handy when it comes to creating manager classes. They enhance code readability, providing a clear syntax for accessing and modifying private variables in scripts.

Free download: Indie Game Marketing Checklist

Download now

Category

programming

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free