So here is the code, right now i only spawn each frame x Prefabs (Its a simple Game im new to unity so the player is a ball and dodges stuff etc. So i have an amount of prefabs (Floors) that is spawning in front of the palyer)


    public static int numSpawned = 0;
    //Creates an Array to store PreFabs into it
    public static GameObject[] thePath;
    //Sets the x value of the spawning postion to 100
    public int SpawningDistance = 100;
    
    public int numToSpawn = 6;

//Calls the PreFabs Folder
    private void Start()
    {
        thePath = Resources.LoadAll<GameObject>("PreFabs");
    }
    //Sets the Spawn Position and ++ the numSpawned
    void SpawnRandomObject()
    {
        int withItem = Random.Range(0,6);

        GameObject myObj = Instantiate(thePath[withItem]) as GameObject;

        numSpawned++;

        myObj.transform.position = transform.position + new Vector3(0, 0, 0);
    }

    //Til now it Spawns every Frame so thats what you have to fix
    void Update()
    {   //compares the Values
        if (numToSpawn > numSpawned)
        {
            //where your object spawns from
            transform.position = new Vector3(SpawningDistance, 0, 0);
            SpawnRandomObject();

            SpawningDistance = SpawningDistance + 100;
        }
    }

Til now its the problem that i dont know how to controlle the spawning amount and speed so i need help for that. All Prefabs are beeing stored in an array and then spawned randomly out of it.

1

There are 1 best solutions below

4
On

Instead of using method SpawnRandomObject() every frame, you could create coroutine and yield WaitForSeconds(value).

[SerializeField] private float delaySpawnInSeconds = 0.5f;

...

private void Start()
{ 
    thePath = Resources.LoadAll<GameObject>("PreFabs");
    StartCoroutine(SpawnFloors());
}

Our coroutine:

private IEnumerator SpawnFloors()
{
    while (numToSpawn > numSpawned)
    {
       //SpawnRandomObject();  //if U want to spawn object then wait
       yield return new WaitForSeconds(delaySpawnInSeconds);
       SpawnRandomObject();  //if U want to wait then spawn object
    }
}

Doc: https://docs.unity3d.com/Manual/Coroutines.html

To get spawning amount, you could use Captain Skyhawk's idea to:

Keep an array of spawned objects and check the count.

Arrays: Doc: https://docs.unity3d.com/2018.4/Documentation/ScriptReference/Array-length.html

You can also use lists, for example:

private List<GameObject> exampleList = new List<GameObject>();
private int sizeOfExampleList;

...\\Add items to the list in the code.\\...

private void exampleMethod () 
{
    sizeOfExampleList = exampleList.Count;
}

...

I hope I helped You! :-)