Hi,

I am currently trying to create a game where there are random objects spawned depending on the player’s score. I have created a spawn script based on the ‘Infinite Runner’ tutorial that uses several if/else statements to determine which array of objects should be spawned. (I tried a switch statement but wasn’t quite able to get it to work – I am a novice coder).

I’ve been trying to figure out a way to get the arrays into different object pools. I have watched the object pooling video live training but I didn’t quite understand how it could apply to this situation where I am spawning different objects from different arrays.

Any information on where to start or how to better optimize this would be greatly appreciated! :slight_smile:

Code below:

public GameObject[] obj;
public GameObject[] obj2;
public GameObject[] obj3;
public float spawnMin = 1f;
public float spawnMax = 2f;
public int playerScore;

void Start() {
	Spawn ();
}

void Spawn()
{
	if(playerScore < 10) {
		Instantiate(obj[Random.Range (0,obj.GetLength(0))], transform.position, Quaternion.identity);
		Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
	} else if(playerScore <20) {
		Instantiate(obj2[Random.Range (0,obj2.GetLength(0))], transform.position, Quaternion.identity);
		Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
	} else if(playerScore <30) {
		Instantiate(obj3[Random.Range (0,obj3.GetLength(0))], transform.position, Quaternion.identity);
		Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
	}
	}
}

You’re right to use if statements for the relative comparisons, switch statements can only be used to compare specific values. I don’t see much wrong with your code although a potential problem if it’s not by design is that you could spawn the same GameObject more than once. If that’s not your intention you could get around it by keeping an array of the indices of your GameObject array that haven’t been chosen and then use those as the random indices, taking out each as it’s used. There’s nothing really wrong with the structure of your code that I can see, normally I’d say boilerplate code is a prime target to get refactored but honestly with something this small it’s not really necessarily and may even over-complicate it. Just to show you what it might look like for future reference in larger projects:

public void Spawn()
{
    if (playerScore < 10) Spawner(obj);
    else if (playerScore < 20) Spawner(obj2);
    else if (playerScore < 30) Spawner(obj3);
}

public void Spawner(GameObject[] gos)
{
    Instantiate(gos[Random.Range(0, gos.GetLength(0))], transform.position, Quaternion.identity);
    Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}

The idea is to encapsulate repetitive tasks for re-use but again, I don’t think you have to worry about it in this case.