I made a script that spawns X amount of asteroids over a certain area. After I made the script an error in the console stated that “not all code returns a value”. Here’s my script:
public GameObject asteroid;
public Vector3 spawnValues;
public int asteroidCount;
// Use this for initialization
void Start ()
{
StartCoroutine (SpawnAsteroids ());
}
// Update is called once per frame
IEnumerator SpawnAsteroids ()
{
while (asteroidCount <= 30)
{
asteroidCount = asteroidCount + 1;
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (asteroid, spawnPosition, spawnRotation);
}
}
}
Thanks in advance :).
A coroutine need to have at least one yield statement or it doesn’t count as coroutine. You may want to do either:
IEnumerator SpawnAsteroids ()
{
while (asteroidCount <= 30)
{
asteroidCount = asteroidCount + 1;
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (asteroid, spawnPosition, spawnRotation);
yield return null;
}
}
this would wait one frame between each asteroid spawn. If you want to wait longer you would do
yield return new WaitForSeconds(5.0f);
instead of
yield return null;
This would wait 5 seconds between each spawn.
Thanks @Bunny83 . The error is going, but for some reason none of the asteroids are spawning. Any ideas as to why?