Trouble with Instantiate and Coroutines

I’m trying to instantiate a single GameObject after 1-3 seconds, and wait another 1-3 seconds and instantiate another. At the same time, I am trying to instantiate these objects at different heights, and later make them move. I have gotten the different heights down, but the GameObjects either instantiate one after another or one and no more. Can someone please help me with this? Also, suggestions on how to move the instantiated GameObject negatively on the x-axis.

Here’s my code

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public GameObject JumpPad;
    public GameObject SpawnPoint;
    int x = 0;

    // Use this for initialization
    void Start () {
        StartCoroutine(Delay());
    }

    IEnumerator Delay(){
        if (x == 0)
        {
            float SpawnTimeDifference = Random.Range(1, 3);
            yield return new WaitForSecondsRealtime(SpawnTimeDifference);
        }
        else
        {
            yield return new WaitForSecondsRealtime(1 / 10);
        }
    }


        // Update is called once per frame
        void Update () {
        if (x == 1) {
            float SpawnHeight = Random.Range(0, 15);
            Rigidbody ClonedJumpPad = Instantiate(JumpPad, new Vector3(SpawnPoint.transform.position.x, SpawnPoint.transform.position.y + SpawnHeight, SpawnPoint.transform.position.z), Quaternion.identity) as Rigidbody;
            x = 0;
        }
        else {
            Delay();
            x = 1;
            Delay();
        }
       
    }
}

You could change it to something like this:

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

public class Test : MonoBehaviour {

    public GameObject JumpPad;
    public GameObject SpawnPoint;
    int x = 0;

    // Use this for initialization
    void Start()
    {
        StartCoroutine(Delay());
    }

    IEnumerator Delay()
    {
        while (true)
        {
            float SpawnTimeDifference = Random.Range(1, 3);

            yield return new WaitForSecondsRealtime(SpawnTimeDifference);

            float SpawnHeight = Random.Range(0, 15);

            GameObject ClonedJumpPad = Instantiate(
                JumpPad,
                new Vector3(
                    SpawnPoint.transform.position.x,
                    SpawnPoint.transform.position.y + SpawnHeight,
                    SpawnPoint.transform.position.z),
                Quaternion.identity) as GameObject;

            ClonedJumpPad.GetComponent<Rigidbody>().AddForce(Vector3.right * -10);
        }
    }
}

Thanks, that worked perfectly :slight_smile: