Balanced Spawning System

How to Spawn based on a distribution table

Distribution Table

1 Common
2 Common
3 Common
4 Common
5 Common
6 Rare
7 Rare
8 Epic

Distribution Table Script

[SerializeField] private float _minPosX, _maxPosX, _startPosY;

//power up config
[SerializeField] private float _minSpawnIntervalPowerup = 3f;
[SerializeField] private float _maxSpawnIntervalPowerup = 7f;

[SerializeField] private int[] _powerUpWeightTable;
[SerializeField] private GameObject[] powerUpsPrefabs;
[SerializeField] private int _total = 0;
[SerializeField] private int randomNumber;
foreach (var weight in _powerUpWeightTable)
{
_total += weight;
}
while (_stopSpawning == false)
{
//random spawn time
float spawnIntervalPowerup = Random.Range(_minSpawnIntervalPowerup, _maxSpawnIntervalPowerup);
//wait first
yield return new WaitForSeconds(spawnIntervalPowerup);
//random spawn pos
Vector3 spawnPos = new Vector3(Random.Range(_minPosX, _maxPosX), _startPosY, 0);

//spawn random powerup
randomNumber = Random.Range(0, _total);
for (int i = 0; i < _powerUpWeightTable.Length; i++)
{
if (randomNumber <= _powerUpWeightTable[i])
{
Instantiate(powerUpsPrefabs[i], spawnPos, Quaternion.identity);
break;
}
else
{
randomNumber -= _powerUpWeightTable[i];
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.