Gameobject SetActive in Array

Hey,

i searched on google, this site and stack overflow but didn´t find a proper soultion of my error.

I want to setActive a specific gameobject in an array true and other false. The Array contains all GameObjects which I want to let check. When i run UseSkin i got this Error message:

NullReferenceException: Object reference not set to an instance of an object

And yes, this method is run, when a button is clicked. UseSkin got the skinID from the button, e.g. 0, 1 or some other numbers. All in range of the array. Array length is 32 (for debuggin only to 2) and the first skin is skins0.
And here is the code snippet

public GameObject[] skins;

    public void UseSkin(int skinID)
    {
        for (int i = 0; i < 2; i++)
        {
            if (i == skinID)
            {
                skins[i].SetActive(true);
            }
            else
            {
                skins[i].SetActive(false);
            }
        }
    }

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

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

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

Are you planning on initializing skins in code? Then don’t make it public. Are you planning on initializing it from the editor? Then make really sure you do.

Hey Kurt, thanks for your fast response.

I already “drag and Droped” the skins in the array, so I can faster enable and disable them. The array lenght is also 32.

And yes, I know what is NULL and what it says, when I didn´t assigned a gameobject (hopefully).

Also here you can see, that I assign all the skins into the array, which I want to have. Thats why I can´t figure out, where the problem is…

Didja put the script on ANOTHER gameobject by accident? Find out by printing the name.

Problem solved. At first, it was on a wrong gameobject, which got the script in runtime.
After solving this problem I used the right “GetComponentInChildren”. Kurt, I thank you for your support. Sometimes i need a bit space to look on the project, but at the end, everything works.