Object reference not set to an instance of an object Problem, HELP!!

Hello.
Next will run good.

But it show the message :
NullReferenceException: Object reference not set to an instance of an object
Switch.Update () (at Assets/Scripts/…Switch.cs:27)

if (index == 0)
{
background[0].gameObject.SetActive(true); // Here is it !!
}

That message is shown only at HOME UI not in others.

Thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Switch : MonoBehaviour
{

    public GameObject[] background;
    int index;

    void Start()
    {
        index = 0;
    }

    void Update()
    {
        if (index > 5)
            index = 5;

        if (index < 0)
            index = 0;

        if (index == 0)
       {
          background[0].gameObject.SetActive(true);
       }
    }

    public void Next()
    {
        index += 1;

        for (int i = 0; i < background.Length; i++)
        {
            background[i].gameObject.SetActive(i == index);
        }
        Debug.Log(index);
    }

    public void Previous()
    {
        index -= 1;

        for (int i = 0; i < background.Length; i++)
        {
            background[i].gameObject.SetActive(index == i);
        }
        Debug.Log(index);
    }

}

Always the same, ALWAYS.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

You have an unassigned entry somewhere in your background collection.