When and where should you use setters and getters? I’m guessing it’s instead of public variables for a structure?
setters
and getters
are mutators and accessors, they are methods used to control changes to a variable.
You can control access level for both the getter
and setter
methods independently (ex: have the getter public
, but have the setter private
so a different script can read it, but won’t be able to change it). You can even do some additional logic every time any script tries to access it.
example:
using UnityEngine;
using System.Object;
public class SomeClass : MonoBehaviour
{
// you could add [SerializeField] here
private Object obj;
private Object counter = 0;
// getter
public Object getObject() {
counter++; // side effect (unless really required, may be considered as bad practice)
Debug.Log("Someone asked " + obj.ToString() + " " + counter + " times!"); // will output number of Object read to the console
return obj;
}
// setter
private setObject(Object objParameter) {
obj = objParameter;
// some other logic
// if (something) { doSomething(); }
}
}
Note that getObject
is public and setObject
is private.
The obj
variable won’t show in the Unity inspector as it is private
.
You could add SerializeField on top of it to display it in inspector.
Watch out for side effects.
Sometimes, it can be very handy to use Mathf.Clamp in your setter to make sure value is always between two values.
You can refer to differences-between-getter-and-setter-and-a-regular-variablec on stackoverflow for other differences and here’s a similar Unity related question. You may also read about Properties on msdn documentation
You use them to run code when the user read/writes to the variable.
In other words you use them WHEN YOU NEED TO DO SOMETHING when they are changed or perhaps read.