Trying to get a group of enemies to attack but with a random delay for each

Hey everyone!

I need some help getting a group of enemies to move toward the player, but not all starting at the same time. I would like to get them to each have a random delay. Right now, there doesn’t seem to be any random effect at all.

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

public class EnemyMovement : MonoBehaviour
{

    public Transform target;
    public Transform enemy;
    public float enemySpeed;

  

    void Start()
    {
        StartCoroutine(EnemyMovementTimer());
        enemySpeed = 0.4f;
      
    }

    IEnumerator EnemyMovementTimer()
    {
        while(true)
         {
            int wait = Random.Range(0, 5);
            yield return new WaitForSeconds(wait);
         }
      
    }

    void Update()
    {
       
        transform.LookAt(target);
        transform.Translate(Vector3.forward * enemySpeed * Time.deltaTime);
    }
}

Hi,

I think you’ve forgotten to code in your attack function, so although your code is waiting a certain amount of time, once that time is over, the coroutine ends, and nothing happens! If you want your enemy speed to change after waiting, put that in the coroutine, not after you call it, as the code will not pause by calling said coroutine.

Here is what you might need to do.

void Attack(int damage){

Debug.Log(“Attacked for: “ + damage);

}

IEnumerator EnemyMovementTimer()

{

int wait = Random.Range(0,5);

Attack(10);

}

NOTE: I didn’t see the purpose of the “while true” statement, so I removed it. It seems you still need to get used to scripting, so maybe consider checking out the beginner tutorials?

Regards,

Miggi124

P.S: You can change the attack function to a move function if you want. I’m also happy to provide some more cohesive code if needed.

Awesome! Thank you! Putting the enemySpeed into the coroutine got things working! Yeah, definitely going to check out the beginner series. Thanks again!

Hi,

I’m happy to help (: If you need anything else, let me know.

Kind Regards,

Miggi124