IEnumerator waitSpawner() { yield return(new WaitForSeconds(startwait)); // wait for sstartwait and then executes the code bellow while (!stopSpawn) { CurrentShape = Random.Range(0, shape.Length); CurrentspawnPosition = new Vector3(Random.Range(-randomPosition.x, randomPosition.x), 1, Random.Range(-randomPosition.z, randomPosition.z)); CurrentMaterial = Random.Range(0, material.Length); GameObject holderShape = shape[CurrentShape]; target t = holderShape.transform.GetComponent <target>(); if (t != null) { t.changeMaterial(material[CurrentMaterial]); Instantiate(holderShape, CurrentspawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation); } yield return(new WaitForSeconds(spawnRate)); } }