How come this simple random jumping script doesn't work?

Viewed 36

so I am currently creating a simple platformer enemy that is meant to jump at random intervals, I want the enemy to do it every 2-5 seconds. While this script should work in theory (I cannot see anything wrong with it) when I run Unity, the enemy just doesn't move. I added in the Debug.Log() lines to try to figure if it was running but the force was too small or to see if it was getting stuck in the waiting state, however the console repeats nothing but "Not Waiting". So it never even runs the Delay in the first place.

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

public class JumperMovement : MonoBehaviour
{
    Rigidbody2D rb;
    public float jumpForce;
    bool jump = false;
    bool waiting = false;

    private void Awake()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        if (jump)
        {
            Vector2 motion = new Vector2(0f, jumpForce);
            rb.AddForce(motion, ForceMode2D.Impulse);
            Debug.Log("Jumping");
            jump = false;
            Delay();
        } else if (!waiting)
        {
            Debug.Log("Not Waiting");
            Delay();
        }
    }

    IEnumerator Delay()
    {
        waiting = true;
        int delay = Random.Range(2, 6);
        Debug.Log("Waiting");
        yield return new WaitForSeconds(delay);
        jump = true;
        waiting = false;
    }
}

I also tried to just put all the code into a loop in the co-routine but I got the same result. I've not used them much so don't know much about them so if someone can explain why this doesn't work as well that would be super useful.

    IEnumerator Delay()
    {
        while (true)
        {
            int delay = Random.Range(2, 6);
            yield return new WaitForSeconds(delay);
            Vector2 motion = new Vector2(0f, jumpForce);
            rb.AddForce(motion, ForceMode2D.Impulse);
        }
    }
1 Answers

There's a couple of things causing issues here:

  1. Coroutines should be started with the StartCoroutine(coroutine) method, else they will be ran as normal code, which is why waiting seems to always be false. (Delay() is ran without pausing, meaning waiting = true and waiting = false happens immediately)`
  2. RigidBody.AddForce is a physics operation, meaning it should be ran within the FixedUpdate method, and not in the normal Update method. If you want to run AddForce inside the Coroutine, use yield return new WaitForFixedUpdate()
Related