Please don’t use Find for this! It is extremely expensive! And unreliable!
This function only returns active
GameObjects. If no GameObject with name can be found,nullis returned.
Especially since it looks like you want to use this for prefabs that only exist in the Assets and not in the Scene this will always return null as it only finds objects from the Scene.
Rather use an array like
public GameObject[] Prefabs;
reference your objects here and simply do
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f)); Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
To your IEnuemrator … well, you never start this as a Coroutine so it is simply never running.
You can do it directly in Start using StartCoroutine
private void Start()
{
StartCoroutine(Spawn());
}
private IEnumerator Spawn()
{
while (true)
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
actually you could even directly use
private IEnumerator Start()
{
while (true)
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
If Start is declared as IEnumerator Unity automatically runs it as a Coroutine.
Or in such a simple case you could even use InvokeRepeating like
private void Start()
{
// second parameter is the initial delay
// last parameter the repeat interval
InvokeRepeating(nameof(Spawn), 0, 1.0f);
}
private void Spawn()
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
}