GetComponent in Start not getting the component.

Hello,

I’m doing this in my script :

void Start () {
    _pRenderer = transform.GetChild(1).GetComponent<SpriteRenderer>();
}

The thing is, it doesn’t get the component, so i have to trick with this *

    public void ChangeColor(Color color)
    {
        if(_pRenderer == null)
                _pRenderer = transform.GetChild(1).GetComponent<SpriteRenderer>();
        _pRenderer.color = color;
    }

I thougt Start was called when everything is ready, Am I wrong ?

Well, as soon as you don’t dynamically instantiate the children later, yes getting the component in Start will definitely work. However maybe you call your ChangeColor method too early? Have you tried placing Debug.Logs inside your Start method and in side your ChangeColor method?

If you actually call ChangeColor later another problem could be that you access the wrong object or the object is deactivated in which case Start won’t run until the object is activated and one frame has passed.

However all this can be avoided by just setting up the reference in the inspector. Using a hardcoded child index is also not recommended. If you add a SerializeField attribute to your _pRenderer variable you can assign a value through the inspector. Just drag the desired child object onto the variable in the inspector. This reference will be saved.