NullReferenceException in foreach (help!)

I’m new to arrays and foreach. I’ve got code that works, and it does what I want it to do: change the colour of a bunch of objects. However, it’s throwing errors at line 26 (labelled below) and I’m not sure why. Could anyone help me understand what I’m doing wrong? Thanks in advance.

Error:
NullReferenceException: Object reference not set to an instance of an object
turnColourChanger.FixedUpdate () (at Assets/scripts/turnColourChanger.cs:26)

    void Start()
    {
        musicBar = GameObject.FindGameObjectsWithTag("musicBar");
    }

    void FixedUpdate() {

        foreach (GameObject component in musicBar) {

            //LINE 26:
            musicBarComponents = component.transform.parent.GetComponent<SpriteRenderer>();

            if (enemyTurnBar == true) {
                musicBarComponents.color = playerTurnColour;
            }
            else {
                musicBarComponents.color = enemyTurnColour;
            }
        }
    }

I’m also new at this coding thing. Strugling with the structure of the language.

But, … I’d try adding ‘SpriteRenderer’ in front of ‘musicBarComponents’. Maybe it helps.

Some GameObject with the tag “musicBar” does not have a parent, but exists in the root of the hierarchy.

This was it! Thanks very much.

1 Like

Thanks for your reply. It turned out I hadnt managed items in my heirarchy properly. Best of luck figuring out Unity as well :slight_smile: