0
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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". \$\endgroup\$ – Nikaas Jul 22 '18 at 9:15
  • \$\begingroup\$ @Nikaas Ok, thank you very much, that helped to clear up my confusion about whether or not SpriteRenderer was a type. \$\endgroup\$ – Kensington Jul 28 '18 at 1:25
0
\$\begingroup\$
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).

\$\endgroup\$
  • \$\begingroup\$ 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) \$\endgroup\$ – Kensington Jul 28 '18 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.