Search code examples
c#arraysnullskipunity-game-engine

skipping an array when it is null


I have objects in my 2d game that are in an array list. These objects instantiate other objects in the game. Which ones that instantiate is based on random. However, these may be destroyed during gameplay. The code still tries to look for the destroyed Transform and so I told it to only instantiate from the array when it isn't null, fixing the error message. Still, the behavior remains. As one of these arrays spawns a gameObject every set number of seconds, it can still decide to spawn from an array that is null. When it randomly selects an array that is null, there is a time period where the play has to sit and wait for something to happen, which is of course unacceptable. How do I tell the game that when an array is null, to skip it and go to the next one, in order to get rid of that waiting period in the game? I also am aware that void doesn't return anything. It's just a placeholder at the end of the script because I can't type in break or continue since it's not a for loop. I posted this before and once the error message left I thought that was the end of it. So sorry for posting it a second time. Thanks in advance.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;


public class podControl : MonoBehaviour {


public Transform [] spawns;
public float spawnTime = 6f;
public float secondSpawnTime = 3f;      
public GameObject podPrefab;



void Start ()
{

    InvokeRepeating ("landingPod", spawnTime, secondSpawnTime);

}



void landingPod ()
{

    int spawnIndex = Random.Range (0, spawns.Length);

    if (spawns[spawnIndex] != null) {

        Instantiate (podPrefab, spawns [spawnIndex].position, spawns [spawnIndex].rotation); 

    }
    else {
        if (spawns [spawnIndex] = null)
            return;

    }
}   

}


Solution

  • You could simply keep looking for a valid spawn before you Instantiate it :

    void landingPod()
    {
    
        int spawnIndex = Random.Range(0, spawns.Length);
    
        while(spawns[spawnIndex] == null)
        {
            spawnIndex = Random.Range(0, spawns.Length);
        }
    
        Instantiate(podPrefab, spawns[spawnIndex].position, spawns[spawnIndex].rotation);
    
    }
    

    And you had this where you do your return :

    if (spawns[spawnIndex] = null)
    

    By just having = and not == you're not verifying if its null but giving this spawns[spawnIndex] the null value.