One the objects in array run out, how do I stop from creating new objects?

Hello all, I’m using an list called ArrayofTiles to store some GameObjects.
Then I’m creating a random item and returning it to another function and removing the returned GameObject from the list.
However once the list is empty, I want it to stop returning the objects.
Currently it is returning the last object every time once it’s empty.
Please help.

    {   
        if(arrayOfTiles.Count>0)
        {
            
            randomTileID = UnityEngine.Random.Range(0,arrayOfTiles.Count-1);
            randomItem = arrayOfTiles[randomTileID];
           // Debug.Log("randomTileID "+ randomTileID+"\nrandomTileID name-->"+arrayOfTiles[randomTileID].name);
            arrayOfTiles.RemoveAt(randomTileID);
            
        } 
           return randomItem;
        } 

It has to return something. Perhaps you want it to return null?

Just set randomItem to null when the count is zero.

Also, it looks like perhaps randomItem is a class variable? That’s kinda weird… why return it if you’re modifying it…?

1 Like

Thanks for the solution. Yes, it worked.
I’ll look into the optimization of class variable.