Help with component issue

I have difficulty in understanding how the GetComponent thing works, specially when it involves parents and children.
I’m experimenting with changing the fox’s color when it hits something, but i don’t understand exactly what’s happening.

	public SpriteRenderer renderer;


void Start () {

	animator = GetComponent<Animator>();
	attackers = GetComponent<Attackers>();
	renderer =  GetComponent<SpriteRenderer>();
 }

in this case i managed to have the fox spawn entirely black. My first question is: why did i have to drag and drop the Body’s (fox’s child) Sprite Renderer component to the Sprite Renderer slot (see image below)? Shouldn’t the line “renderer=GetComponent();” find it? I even tried to replace it with GetComponentsInChildren, without success.

Second question - I moved the line

 renderer.color = new Color(0f, 0f, 0f, 1f);

to the OnTriggerEnter2D method, and then it stopped having any effect - the fox never gets black, even though i’ve already managed to have it jump over the grave stone and all. What might be the issue?

You don’t have to drag the Body sprite renderer in the field. It works this way:

  • If you declare a public variable, you’ll get a field in the Inspector in which you could assign a reference, but it’s not mandatory.
  • If you assign a reference in the Inspector, the script will use that reference unless you change that reference inside the script itself (i.e.: reference assignment in script overwrites the Inspector assignment at runtime). If you have the reference assigned in the script, you can leave the Inspector field empty.
  • If you want to get the component from the child object, you need to use the GetComponentInChildren, without the “s”.

Regarding the other problem with the color, it’s hard to understand why it’s not working without looking at the code of the OnTrigger method, it seems it loses for some reason the reference to the sprite renderer.

Privacy & Terms