0

Hi i make a 2D endlessrunner and now im write the script for an obstacelspawner but an error is still there. here is the code for the spawner

IEnumerator SpawnRandomObstacle()   
{
    yield return new WaitForSeconds(Random.Range(1.5f, 4.5f));
    int index = Random.Range(0, obstaclesToSpawn.Count);
    while (true)
    {
        if (!obstacleToSpawn[index].activeInHierarchy)
        {
            obstaclesToSpawn[index].SetActive(true);
            break;
        }
        else
        {
            index = Random.Range(0, obstaclesToSpawn.Count);
        }
    }

    StartCoroutine (SpawnRandomObstacle ());
}      
General Grievance
  • 4,555
  • 31
  • 31
  • 45
knack
  • 1

1 Answers1

0

You should put your method/coroutine inside a monobehaviour class:

public class TrainingManagerEditorFreeRouteManager : MonoBehaviour {

    IEnumerator SpawnRandomObstacle()   
    {
        yield return new WaitForSeconds(Random.Range(1.5f, 4.5f));
        int index = Random.Range(0, obstaclesToSpawn.Count);
        while (true)
        {
            if (!obstacleToSpawn[index].activeInHierarchy)
            {
                obstaclesToSpawn[index].SetActive(true);
                break;
            }
            else
            {
                index = Random.Range(0, obstaclesToSpawn.Count);
            }
        }

        StartCoroutine (SpawnRandomObstacle ());
    }      
}

For a better understanding you can read what namespaces are. They're used as scopes to organize your code. If you dont put any, its the globall namespace, and you cannot put methods/corroutenes directly there.

rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47