C# Call Once or Call at Intervals

Hi,

I am trying to make an AI follow the player and shoot at them at intervals.

At present I cannot think of the appropriate way of writing a delay between calling the function.

IEnumerator followThePlayer () {
        transform.position = Vector3.MoveTowards (transform.position, new Vector3(transform.position.x, player.position.y, transform.position.z), 1f * Time.deltaTime);
        yield return new WaitForSeconds(5);
        shootThePlayer ();

Would setting a boolean called isActive on or off a good way of delaying the attack being called in your opinion?

Thanks.

I would create a field where you can set a delay, and then in the ShootThePlayer script create a timer that checks the time since tha last shot against the newly created field. Making the field adjustable in the inspector then allows you to quickly set the desired delay.

1 Like

Thank you, I have done so and it works great.

public float shootingDelay = 5f;

void Update () {
        shootingDelay -= Time.deltaTime;
}

void shootThePlayer () {
        if(shootingDelay <= 0.0f)
        {
//Shoot stuff
shootingDelay = 5f;
}
}
1 Like