When you call “myGameObject.GetComponent(…)” on a GameObject, you’re calling a function on the GameObject which looks through each of its attached Components and returns a reference to one where the type matches.
Inside your script, you can save that reference to a variable. For instance…
Animator myAnimator;
void Start()
{
myAnimator = GetComponent<Animator>();
}
Similarly, you can populate that variable in the Inspector by dragging the Animator in there. That tells Unity that when it instantiates the GameObject it needs to put a copy of the reference to the Animator it creates in that variable.
Either way, as long as that Animator exists it will be in the same place in memory, so instead of “finding” the reference every single time, you can just keep a copy and re-use it.
This is a really good use case for a property which only provides a ‘get’ function. You don’t want to make the variable public because then anything can change the Animator reference and break it - that’s bad! But you do need other stuff to be able to access it, and a property with a get function does that nicely.
You might find that you have some reason to provide a private ‘set’ function in there. For instance, maybe your Animator changes from time to time, and you want to raise an event when that happens.
Another common use for ‘set’ properties, whether public or private, is to sanitise the values being accepted. Say I have an input variable which needs to be between 0 and 1, but I want anything to be able to set it. The following code would do that nicely:
private float input = 0;
public float Input
{
get { return input; }
set { input = Mathf.Clamp01(value); }
}
This way I can still allow anyone to set values to my input variable, while being confident that it will always stay within the valid range.