GetComponent null, but it's attached to gameobject

Hey everybody,
so I wrote a script, which creates two objects. In one of these object scripts, it want to get the objects SpriteRenderer component and it’s attached to!
But everytime I run the game it says NullReferenceException.
The line with the error is a comparison between the spriterenderer color of the objects, so I check first if one of them is null.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class LockDoor : MonoBehaviour {

    public List<Color> colGen = new List<Color>();
    public int colNow;
    public int i;
    public Transform doorsGO;
    public Animation lockAnim;
    public Controls controls;
    public ScoreManagement scoreScript;

    private new SpriteRenderer renderer;

    void Awake()

        // Find GameObejcts
        doorsGO = GameObject.FindWithTag("doors").transform;
        scoreScript = GameObject.Find("Score").GetComponent<ScoreManagement>();
        //doorsGameObject = GameObject.Find("doors");
        controls = doorsGO.GetComponent<Controls>();


    // Use this for initialization
    void Start () {

        // GetComponents

        lockAnim = GetComponent<Animation>();
        lockAnim["LockTheDoor"].speed = 2.0f;

        // Liste mit Farben


        // Change Color für Schlüssel

        renderer = GetComponent<SpriteRenderer>();
        colNow = Random.Range(0, colGen.Count);
        renderer.color = colGen[colNow];

        // Change Color für Türen

        foreach (Transform colChi in doorsGO)
            SpriteRenderer col = colChi.GetComponent<SpriteRenderer>();
            i = Random.Range(0, colGen.Count);
            col.color = colGen*;*



  • IEnumerator WaitForAnimation () {*

controls.enabled = false;
scoreScript.enabled = true;
print(“You’ve locked the door!”);
yield return new WaitForSeconds(lockAnim.clip.length);


void OnTriggerEnter2D(Collider2D other)

SpriteRenderer othCol;
othCol = other.gameObject.GetComponent();
if (renderer != null)
if (renderer.color == othCol.color) // here is the line with the error
print(“Wrong door!”);



Thanks and sorry for my bad english!

It’s been ages and not really related to a question, but the post is a perfect opportunity to explain an issue I was having.

I was instantiating a prefab from within a Coroutine, and calling GetComponent immediately afterwards.
Turns out, I had to yield return null before attempting to getComponent inside this corutine, to give unity a chance to set-up the components.

That’s true because when breakpointing, the Start() method in the instantiated prefab wasn’t hit until the next frame.