Rajan Phatak
Rajan Phatak

Reputation: 524

Take action at a random point during horizontal movement in unity

I have a GameObject which moves from left to right at a particular speed. I want to take a certain action randomly during the movement of that object. However, I am unsure on how can I randomize such action. Here is my code. I am currently able to perform the action after a specific time but instead not able to run same logic to run at a random location instead of time interval

public GameObject[] Prefabs;

    public float speed;

    public float generateTime;

    // Start is called before the first frame update
    void Start()
    {
        speed = Random.Range(1,5);

        StartCoroutine (generator());
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(new Vector2(1f*Time.deltaTime*speed, 0f));
    }

    IEnumerator generator()
    {
// Currently this action takes place after a particular time
        yield return new WaitForSeconds(generateTime);
        spawnProducts();
    }

    void spawnProducts()
    {
        // This action will be performed at random point
    }

    void OnBecameInvisible()
    {
        Destroy(gameObject);
    }

Upvotes: 0

Views: 89

Answers (1)

KiynL
KiynL

Reputation: 4266

Set the waiting time randomly and also your IEnumerator permanently.

IEnumerator generator()
{
    while (true)
    {
        yield return new WaitForSeconds(Random.Range(1,generateTime));
        spawnProducts();
    }
}

Upvotes: 1

Related Questions