Unity Developer — Spawn Percentage

Christopher Graf
3 min readJun 24, 2021

--

To add variety to our game, we have made numerous types of enemies and of powerups. Some of the enemies are tougher than the others and some of the powerups are more helpful than the others. So it would make sense for both of these to spawn less than the others. Here’s how we can change the spawning percentages, rather than make them all equal.

Previous to this, when spawning multiple types, we would write something along the lines of ‘int randomType = Random.Range(0, 6);’ if 6 was the number of types. In this case, each number would be as likely to appear as the other. This is exactly what we are going to change.

First off, we are going to change that line of code to ‘float randomType = Random.Range(0.0f, 1.0f);’ Now the value can be anything from 0 to 1 and this can be easily split into percentages. The same could be done with 0 to 100 as well. Use what makes more sense to you.

We are going to be using a long IF-ELSE Statement now. Before that be sure to declare an int for the type number. This will be the value we assign to know what will be instantiated.

Now all you have to do is split up the 0 to 1, or 0 to 100, by percentages depending on what you want spawned more or less. Here is an example.

So enemyType 0 has a 35% chance of spawning, but enemyType 1 has only a 10% chance. If you set up your types in an array and with the Inspector, you can use this number value to instantiate.

Now you can make extremely weak enemies or bigger and tougher ones and you’ll know how to balance accordingly.

--

--

No responses yet