- Home /
Question by
nbarrett123 · Aug 19, 2016 at 01:23 PM ·
c#instantiateprefabarray
Instantiating an array of objects - how can I instantiate a certain prefab only once?
I'm using the following code to randomly instantiate an array of hazards. The array currently consists of 6 hazards. I want to add in one power-up but I only want this to appear in the array once during a round.
Can anyone help?
IEnumerator spawnWaves()
{
inRound = true;
while (true) {
for (int i = 0; i < hazardCount; i++)
{
if (roundEnd == true)
{
inRound = false;
yield return new WaitForSeconds(2);
StartCoroutine("rest1");
yield break;
}
GameObject hazard = hazards[Random.Range(0,hazards.Length)];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(Random.Range(spawnWaitMin, spawnWaitMax));
}
yield return new WaitForSeconds(Random.Range(waveWaitMin, waveWaitMax));
}
}
Comment
Best Answer
Answer by Hellium · Aug 19, 2016 at 01:28 PM
If hazardCount > hazards.Lenght, you will have duplication, unless you keep the following line :
if( hazardCount > hazards.Length )
hazardCount = hazards.Length ;
This is the script I fixed for you :
IEnumerator spawnWaves()
{
List<int> indices = new List<int>();
if( hazardCount > hazards.Length )
hazardCount = hazards.Length ;
inRound = true;
while ( true )
{
indices.Clear();
// Populate list of indices
for ( int i = 0 ; i < hazardCount ; i++ )
indices.Add( i );
for ( int i = 0 ; i < hazardCount ; i++ )
{
if ( roundEnd == true )
{
inRound = false;
yield return new WaitForSeconds( 2 );
StartCoroutine( "rest1" );
yield break;
}
// Select hazard to instantiate
int index = indices[Random.Range(0,indices.Count)];
GameObject hazard = hazards[index];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
GameObject go = Instantiate( hazard, spawnPosition, spawnRotation ) as GameObject;
indices.Remove( index );
yield return new WaitForSeconds( Random.Range( spawnWaitMin, spawnWaitMax ) );
}
yield return new WaitForSeconds( Random.Range( waveWaitMin, waveWaitMax ) );
}
}
Your answer
Follow this Question
Related Questions
How to deal with for loop and array? 0 Answers
Prefabs instantiated from an array are keeping their public int value 1 Answer
OverlapSphere for parallel arrays 1 Answer
How to associate underlying data structure to prefab at runtime? 1 Answer
Instantiating an object as a child of another object 1 Answer