# Clarification on the correct way to call SpriteRenderer

This is probably a dumb question, born from my own ignorance, but I haven't been able to find a satisfying answer yet.

In this post Savlon gives example code for using SpriteRenderer to cycle through two sprites. What exactly is the purpose of the line:

private SpriteRenderer spriteRenderer;


To me this looks like we are storing an instance of the class SpriteRenderer inside the private pointer spriteRenderer. Because in the Start loop they write

spriteRenderer = GetComponent<SpriteRenderer>();


which uses GetComponent to address properties of SpriteRenderer.

Is this correct? If so, what is the advantage to doing this over creating Savlon's code inside a subclass of the SpriteRenderer class?

• Kensington
• The first line means something like "we create a variable named spriteRenderer in which we intend to store/point an object of type SpriteRenderer". The second one means "this is the exact object/instance/value we point/put inside it". – Nikaas Jul 22 '18 at 9:15
• @Nikaas Ok, thank you very much, that helped to clear up my confusion about whether or not SpriteRenderer was a type. – Kensington Jul 28 '18 at 1:25

private SpriteRenderer spriteRenderer;
...
Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
...
}


Keeping a private reference to a Game Object's component is totally normal. It improves the performance as you ask Unity only once to fetch the component, no matter how many times you're going to use it.

You can't create a subclass of SpriteRenderer (because it belongs to a library) nor derive from it (because it's sealed).

• Ok, that makes sense. Thank you very much for your help. (Not sure if this is where I am supposed to put my thanks but I didn't want to make it an answer) – Kensington Jul 28 '18 at 1:23