There are several reasons but the most dominant reason is for Reuse-ability and Easy of the script.
If I write a script that says:
void Start()
{
_object = GetComponent<SpriteRenderer>();
}
Then no matter what object I drop this script on it will get the first SpriteRenderer Component, I will not have to drag anything from the editor. Can save time when using it on a lots of objects.
Then there are times when you do not know what object is going to get passed in and you want to see if it has a component if it does you use it.
void OnCollisionEnter2D (Collision2D col)
{
var go = col.gameObject.GetComponent<IDamage>();
if( go != null )
{
// Do Something
}
}
You cannot just use a field in every instance, you need to know how to access that info when your unsure what object your going to get.
if you want to access more then one you use:
var renderers = GetComponents<SpriteRenderer>();
That will return an array of SpriteRenderers then you can access the individual SpriteRenderers by index.
renderers[index]
member field access is ideal but not always what you will be able to do. Use the tools that best help you to solve your issue. If it works then it works, there is rarely ever just one solution. It typically comes down to the situation, performance, and skill level.
As for your question:
Why couldn’t we have said SpriteRenderer.sprite = hitSprites[spriteIndex]
?
SpriteRenderer is a class. When you use a class and say
SpriteRenderer.sprite
what you are doing is calling a static member of the Class. If you are not familiar with static member and static classes you can do a quick search but your not affecting the particular SpriteRenderer that is in the object you are in fact accessing an instance that is on the heap somewhere an persistent to the Class itself.
Most likely that would cause a compiler error because I do not think that SpriteRenderer has a static field called sprite. You can look it up though if you want it would be a good exercise.
The GetComponent<T>()
returns an Object of T.
The GetComponent<SpriteRenderer>()
returns a specific instance of a SpriteRenderer Class that you are then setting.You can expand the original line like this.
var go = GetComponent<SpriteRenderer>();
go.sprite = hitSprites[spriteIndex];