Using Properties Instead of Public Methods

At this level of coding, why do we still make public methods instead of using properties (get, set) to retrieve variables across differente classes?

such as

   int experiencePoints = 0;
   public int _experiencePoints { get { return experiencePoints; } }

instead of the public method “GetPoints” shown in the video?

is there a coding convention or good coding practice in play here?

Thanks!

1 Like

I would agree that we probably should be using properties more often than we do. Some of the reason for this is Unity’s poor handling of properties in the inspector. Properties simply don’t appear in the inspector. (That actually has changed, but only by using a special modifier field: before the SerializeField, but this still doesn’t work with custom code in the getters/setters).

In this case, a public getter could be done as a property or a method, since we’re simply exposing a getter. There are actually several ways this getter could be handled.

public int ExperiencePoints {get; private set}

This would require no backing field (the compiler creates a hidden backing field for you, but it would not appear in the inspector).

[field: SerializeField]  public int ExperiencePoints (get; private set};

This would actually be shown in the inspector. If you want to use Editor code to display the property in your editor, however, you have to use the special name for the backing field. This feature was added in a relatively recent version of Unity.

void experiencePoints=0;
public int ExperiencePoints
{
    get =>experiencePoints; //in this construction => experiencePoints is equal to {return experiencePoints;}
    private set
    { 
         ExperiencePoints=value;
     }
}

OK thank you very much for your in-depth answer!

My favourite style of coding, which mirrors what Jason Weimann does (a famous Unity developer), is to do as followed:

[SerializeField] int _experiencePoints = 0;
public int experiencePoints => _experiencePoints;

so that _experiencePoints can be updated in the editor only, and the getter allow other scripts a way to get them (without a way for the other scripts to update it, just the editor).

1 Like

hey this is pretty neat, thanks!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms