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. Dismiss Notice

Arrays and gameobjects

Discussion in 'Scripting' started by BluIsBlue, Jan 28, 2021.

  1. BluIsBlue

    BluIsBlue

    Joined:
    Aug 19, 2020
    Posts:
    2
    So, for whatever reason the following code returns 'NullReferenceException: Object reference not set to an instance of an object'

    Code (CSharp):
    1.     GameObject[] spawnpoints;
    2.     public GameObject botpre;
    3.  
    4.     void Start()
    5.     {
    6.         GameObject[] spawnpoints = GameObject.FindGameObjectsWithTag("Respawn");
    7.         BeginMatch();
    8.     }
    9.  
    10.     public void SpawnBot()
    11.     {
    12.         Debug.Log("Spawning " + botcount + " bots");
    13.         foreach(GameObject spawn in spawnpoints)
    14.         {
    15.             if(botcount == 0)
    16.             {
    17.                 return;
    18.             }
    19.             else
    20.             {
    21.                 GameObject a = Instantiate(botpre) as GameObject;
    22.                 a.transform.position = spawn.transform.position;
    23.                 botcount = botcount - 1;
    24.             }
    25.         }
    26.     }
    everything is fine and works properly until you get to the foreach loop. Any ideas how I could effectively use this foreach loop to spawn my bots?
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    here you create a new reference of an array:
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         GameObject[] spawnpoints = GameObject.FindGameObjectsWithTag("Respawn");
    4.         BeginMatch();
    5.     }
    so on your upper variable
    Code (CSharp):
    1. GameObject[] spawnpoints;
    the Object you find, will never get applied.

    Solution would be :

    Code (CSharp):
    1. private GameObject[] spawnpoints;
    2. spawnpoints = GameObject.FindGameObjectsWithTag("Respawn");
     
    mopthrow likes this.
  3. BluIsBlue

    BluIsBlue

    Joined:
    Aug 19, 2020
    Posts:
    2
    Oh jeez! I didn't even realize I accidentally created a new array! Thank you so much! It fixed it right up!
     
    Terraya likes this.