Object not instantiating

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour {

public Transform gap;
public float timer = 1.0f;

    // Use this for initialization
    void Start () {
       
        Spawn();
    }
   
    // Update is called once per frame
    IEnumerator Spawn () {
       
        bool shouldSpawn = true;
        float rand = Random.Range(-3.0f, 3.0f);

        while(shouldSpawn == true){

            Instantiate(gap, new Vector3(transform.position.x,transform.position.y + rand, transform.position.z),transform.rotation);
            yield return new WaitForSeconds(timer);
        }
    }
}

No errors but no objects are being created in the scene. What am I doing wrong?

Looks like you set your Spawn function as a coroutine, but you’re not calling it as a coroutine…

Replace Spawn(); in start with this:

StartCoroutine("Spawn");

No prob!

Actually, now the objects aren’t spawning within the given range on the y axis… C# makes me want to vomit.

You only set the value of rand once and then your while loop uses the same value. This has nothing to do with c#. This would be true of any language.

Yeah, move your random into the while loop:

    IEnumerator Spawn () {
  
        bool shouldSpawn = true;
        float rand;

        while(shouldSpawn == true){
            rand = Random.Range(-3.0f, 3.0f);
            Instantiate(gap, new Vector3(transform.position.x,transform.position.y + rand, transform.position.z),transform.rotation);
            yield return new WaitForSeconds(timer);
        }
    }

Also, you didn’t mention issues with this, but I’m not sure the scope on shouldSpawn… not sure it will work how you probably will want it to. I assume you plan on turning it off, eventually, somehow outside the coroutine (but presumably in Spawner somewhere), and I’m not sure if you can. I don’t really use coroutines a lot, sorry. You may need to declare it at the start of your Spawner script to turn it off within the Spawner script (or something that references this script). Someone can correct me if I’m wrong on that.

You are correct that it should be declared in a way that it can be turned off, but you can also create an IEnumerator variable that can hold a reference to the coroutine and use StopCoroutine to stop it as well. Just not sure if that is what is intended or not.

Yeah, I was aware of StopCoroutine, but I figured with the boolean set up he’s using right now he wouldn’t be using that in conjunction with StopCoroutine, as it wouldn’t quite make sense (for the scope reason I mentioned).