- Home /
how instantiate random enemy only once on random spawn
is it possible to spawn every enemy only once and use every spawn point only once?
here my code :
var spawnPoints : Transform[]; // Array of spawn points to be used. var enemyPrefabs : GameObject[]; // Array of different Enemies that are used. var amountEnemies = 16; // Total number of enemies to spawn.
function newSpawn() {
for (i=0; i<amountEnemies; i++) // How many enemies to instantiate total. { var obj : GameObject = enemyPrefabs[Random.Range(0, enemyPrefabs.length-1)]; // Randomize the different enemies to instantiate. var pos: Transform = spawnPoints[Random.Range(0, spawnPoints.length-1)]; // Randomize the spawnPoints to instantiate enemy at next. Instantiate(obj, pos.position, pos.rotation); } }
By the way, Random.Range(0, enemyPrefabs.length-1)
wont include the last item in the array. Random.Range is exclusive for integers. To get all available indices, you should write Random.Range(0, enemyPrefabs.length)
.
Answer by StephanK · Mar 08, 2011 at 02:05 PM
Easiest way to do this would be using a list instead of arrays. You'd use the same logic as in your script, but after spawning you'd remove the prefab and spawn point from the list, which is as easy as
prefabList.(RemoveAt(index));
'index', in this case would be a random index between 0 and enemyPrefabs.Lenght (-1) obtained each iteraton.
Your answer
Follow this Question
Related Questions
Creating a light in game C# 1 Answer
Randomly Initiate Cubes - Prevent Same Position 0 Answers
Random Position Script 1 Answer
Room generator spawn 1 unique room 1 Answer
How do I spawn a random prefab? 1 Answer