Hi there and thanks for looking. I need some help with my spawn system it works great but i want it to be better and easier to edit at runtime. The whole thing works of off a percentage chance to spawn at the minute i have something that goes like this
zzzsssnnnn
12345678910
z = zombie
s = skeleton
n = nothing
so Zombie has 30% chance
Skeleton has 30% chance
and nothing has 40% chance
I want to be able to just assign a % chance to each enemy and then spawn that enemy based on it’s percentage here is the whole code. If you look at Waves() you will see how i currently assign the percentage to spawn i want this to be easier if someone out there could help that would be great.
using UnityEngine;
using System.Collections;
public class SpawnSystem : MonoBehaviour {
//our variables
public int minEnemies;
public int maxEnemies;
public int maxEnemiesPerWave = 20; // max enemies to spawn not for the wholoe round this is for performance
public int currentEnemies;
public int currentWave;
public float spawnInterval;
public float random;
public int wytches = 0;
public int totalEnemiesForThisRound = 50; // Max enemies to have for the whole round
public int enemiesSpawnedThisWave;// here it would be like how many to spawn ie not max enemies but a threshold
public Transform[] spawnPoints;
[System.Serializable]
public class Enemy
{
public string enemyName;
public int minPercentageToSpawn;
public int maxPercentageToSpawn;
public GameObject enemy;
}
public Enemy[] enemies = new Enemy[11];
// Use this for initialization
void Start ()
{
currentWave = 1;
totalEnemiesForThisRound = 50;
Waves();
StartCoroutine(SpawnLoop());
}
IEnumerator SpawnLoop()
{
while(true)
{
SpawnEnemies();
yield return new WaitForSeconds(spawnInterval);
}
}
// Update is called once per frame
void Update ()
{
if (enemiesSpawnedThisWave == totalEnemiesForThisRound)
{
enemiesSpawnedThisWave = 0;
totalEnemiesForThisRound += 20;
currentWave += 1;
Waves();
}
}
void SpawnEnemies() // start creating some enemies
{
if (currentEnemies <= maxEnemiesPerWave && enemiesSpawnedThisWave != totalEnemiesForThisRound)
{
for (int l_enemy = 0; l_enemy < enemies.Length; l_enemy++)
{
random = Random.Range(1, 11);
if (random <= enemies[l_enemy].maxPercentageToSpawn && random >= enemies[l_enemy].minPercentageToSpawn)
{
Debug.Log(random);
Transform l_obj = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(enemies[l_enemy].enemy, l_obj.position, l_obj.rotation);
currentEnemies += 1;
enemiesSpawnedThisWave += 1;
}
}
}
}
void Waves()
{
switch (currentWave)
{
case 1:// count the min and max to get the % to spawn so 5-9 = 50% 5-6-7-8-9 10% for each number
enemies[0].maxPercentageToSpawn = 5;
enemies[0].minPercentageToSpawn = 1;
enemies[1].maxPercentageToSpawn = 10;
enemies[1].minPercentageToSpawn = 6;
break;
case 2:
enemies[0].maxPercentageToSpawn = 2;
enemies[0].minPercentageToSpawn = 0;
enemies[1].maxPercentageToSpawn = 6;
enemies[1].minPercentageToSpawn = 3;
break;
default:
break;
}
}
}