Home > Software engineering >  How To Spawn Selected Object with SpawnCount
How To Spawn Selected Object with SpawnCount

Time:11-04

Get Object && Get its Count SpawnCount

spawn All 20 Selected Object

See Image Following Code Don't Matter Just Example.

using UnityEngine;

[System.Serializable]
public class ObjectToSpawn
{
    public GameObject Object;
    public int spawnCount;

}
public class LevelSpawner : MonoBehaviour
{
 public ObjectToSpawn[] itemToSpawn; // Select Obstacles To spawn
    public int maxSpawnObject;  // Total Object or Sum of All Spawn Count.
}

CodePudding user response:

So after clarifying things in the comments I'd say you simply want to do

public class LevelSpawner : MonoBehaviour
{
    public ObjectToSpawn[] itemToSpawn; 
    public int maxSpawnObject;

    // Wherever this is called e.g. in "Awake"
    public void Spawn()
    {
        // Keep track how many things you spawned in total
        var counter = 0;

        // iterate given items in order
        foreach(var item in itemToSpawn)
        {
            // Iterate spawnCount times for the current item
            for(var i = 0; i < item.spawnCount; i  )
            {
                // spawn the item
                Instantiate(item.Object);

                // increase the counter
                counter  ;

                // return if max count is exceeded
                if(counter >= maxSpawnObject) return;
            }
        }
    }
}
  • Related