- Home /
Question is off-topic or not relevant
When to use SETters and GETters
When and where should you use setters and getters? I'm guessing it's instead of public variables for a structure?
In part, they're mainly there to create context for the data you're obtaining.
For example, say you have an enemy with 54,037,928 health. Rather than having that variable be public, you set it as private and use GetHealth() to find its current health. Then, you don't have to report the health exactly.
In this manner, you can return a value as precise or imprecise as you want. $$anonymous$$aybe ins$$anonymous$$d of saying it has 26,044,283 health remaining, you would prefer to say that it has 48% (or 48.1%) health remaining. $$anonymous$$aybe you'd rather just round it to the nearest million? That's entirely up to you.
this is a general program$$anonymous$$g question, and simply adds to the clutter here. go ask on stack overflow.
Answer by nug700 · May 18, 2015 at 11:33 PM
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.
$$anonymous$$ainly they make code easier to read. Java does not have get/set and it works fine.
in C++ there were time when youwould end up with:
member->SetValue(member->value++);
now with C# get/set;
member.value++;
Answer by GabLeRoux · May 19, 2015 at 10:03 AM
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