Documentation about scripting properties (get{} , set{})

Hello all :slight_smile: Just watched the Properties intermediate scripting lesson , and don’t get it very well at the end. I searched about it in Scripting API but nothing found. Does anybody know where to find something that can help me with that?

Thank you!

You can just do a search on Google, etc for C# properties. Not sure what the video is about but these kind of properties are not unity specific.

Basically these are known as accessors.

Anytime you want to expose (make available outside this class) a property (a representation of a variable inside your class) you use a property to do it.

The basic idea is inside one of your classes (class A for example) you have some bit of data say a flag for example:

private bool someFlag;

And another class (class B for example) in your project needs to be able to access that flag:

if (oA.someFlag)
{
    // DoSomething
}

In this case, class B cannot actually see the someFlag variable because it is private to class A.

While you could change the declaration from private bool someFlag to public bool someFlag and that change would allow class B to access the someFlag variable, that is not the best way to do it.

The focus with properties is on controlling access.

By using a property wrapper around the variable you can translate the value before the result is returned to the outside world. Also, you can control whether the outside classes can change the value and how they can change it.

A more meaningful example:

Player class

private bool bCurrentlyFacing = Facing.Left;

public property CurrentlyFacing
{
    get { return bCurrentlyFacing; }
}

Enemy class

// if the enemy is facing the same direction as the player
if (player.CurrentlyFacing == enemy.CurrentlyFacing)
    PursuePlayerIfPlayerInFrontofEnemy();
else
    RunAwayFromPlayerIfPlayerBehindEnemy();

This logic is not actually correct. It is simply to illustrate using properties. I just wanted to knock out a quick sample to show how to use properties and illustrate how properties can control access to a class’s private variables.

In this case, the enemy class can see which direction the player is currently facing but the enemy class cannot change the player’s direction. This is because there is no set in the CurrentlyFacing property.

That may have been more confusion but I hope it helps you to better understand how and why properties are used.

1 Like