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.
Instead of using method
SpawnRandomObject()
every frame, you could create coroutine and yield WaitForSeconds(value).Our coroutine:
Doc: https://docs.unity3d.com/Manual/Coroutines.html
To get spawning amount, you could use Captain Skyhawk's idea to:
Arrays: Doc: https://docs.unity3d.com/2018.4/Documentation/ScriptReference/Array-length.html
You can also use lists, for example:
I hope I helped You! :-)