Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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

Discussion in 'Scripting' started by tmcthee, Sep 2, 2019.

  1. tmcthee

    tmcthee

    Joined:
    Mar 8, 2013
    Posts:
    119
    Hi, apologies in advance, I know I'm making some basic error here, but...

    I'm trying to instantiate and destroy gameobjects referenced in an array.

    It works fine when I do it with a single reference like this...

    Code (CSharp):
    1.    public void NextButton()
    2.     {
    3.         Destroy(instance);
    4.         instance = Instantiate(prefabs[whichPrefab], parentTransforms[1]);
    5.     }
    So I expected it to be simple to do the same with an array like this

    Code (CSharp):
    1.    public void NextButton()
    2.     {
    3.         for (int i = 0; i < parentTransforms.Length; i++)
    4.         {
    5.             Destroy(instances[i]);
    6.             instances[i] = Instantiate(prefabs[whichPrefab], parentTransforms[i]);
    7.         }
    8.     }
    But this give a "NullReferenceException: Object reference not set to an instance of an object"

    Can anyone explain what I'm misunderstanding please?
    Thanks in advance
     
  2. CurtisMcGill

    CurtisMcGill

    Joined:
    Aug 7, 2012
    Posts:
    67
    Did you try this...

    Code (CSharp):
    1.     public void NextButton()
    2.     {
    3.         for (int i = 0; i < parentTransforms.Length; i++)
    4.         {
    5.             if (instances[i] == null) continue;
    6.             Destroy(instances[i]);
    7.             instances[i] = Instantiate(prefabs[whichPrefab], parentTransforms[i]);
    8.         }
    9.     }