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?

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);
     }
 }