running the same code in different places
Hi guys,
I wrote the code below to spawn in hazard objects in a random point in a specific area.
public GameObject[] hazardList;
public int hazardCount;
public float startWait;
public float spawnWait;
public float waveWait;
public Vector3 spawnArea;
void Start ()
{
StartCoroutine(HazardWaves());
}
IEnumerator HazardWaves()
{
yield return new WaitForSeconds(startWait);
while(true)
{
for(int i = 0; i < hazardCount; i++)
{
GameObject hazard = hazardList[Random.Range(0, hazardList.Length)];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnArea.x, spawnArea.x), spawnArea.y, spawnArea.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
The issue i am having is that i need to run the same code but in 3 different spawn areas at once. I heard before that if you have to write your code twice then its bad form. So do you guys know how i can call this with 3 different areas without simply copy and pasting the code with a different spawn area V3?
Answer by JedBeryll · Jun 27, 2016 at 06:00 AM
If you add a Vector3 spawnPos as parameter then you can execute the code in 3 different places:
public GameObject[] hazardList;
public int hazardCount;
public float startWait;
public float spawnWait;
public float waveWait;
public Vector3 spawnArea1;
public Vector3 spawnArea2;
public Vector3 spawnArea3;
void Start ()
{
StartCoroutine(HazardWaves(spawnArea1));
StartCoroutine(HazardWaves(spawnArea2));
StartCoroutine(HazardWaves(spawnArea3));
}
IEnumerator HazardWaves(Vector3 spawnArea)
{
yield return new WaitForSeconds(startWait);
while(true)
{
for(int i = 0; i < hazardCount; i++)
{
GameObject hazard = hazardList[Random.Range(0, hazardList.Length)];
Vector3 spawnPosition = new Vector3(Random.Range(-spawnArea.x, spawnArea.x), spawnArea.y, spawnArea.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
Oh i see it now. you are giving the coroutine an input variable. That would do it. Thanks for the help.
Your answer
Follow this Question
Related Questions
Complicated level change problem 1 Answer
Problem with decrement 0 Answers
How to make a global variable in Unity? 5 Answers