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);
}
}