0
votes

I have two functions , I want harmPlayer() should be called after every 5 seconds from Update() function. But the it is getting executed several hundred times from update() functions. I understand the Update() function is getting executed on each frame and is calling everytime the harmPlayer(), then how can i implement wait for 5 seconds'

 IEnumerator HarmPlayer()
    {
        Debug.Log("Inside Harm Player");
        yield return new WaitForSeconds(5);
        Debug.Log("Player Health is the issue");

    }

Here is my Update() function

void Update () {

        transform.LookAt(target);
        float step = speed * Time.deltaTime;
        distance = (transform.position - target.position).magnitude;
        if (distance < 3.5)
        {
           animator.SetFloat("Attack", 0.2f);
            StartCoroutine("HarmPlayer");
        }    
    }
1
That's because your coroutine is getting called on every update, waiting 5 seconds, and then processing the coroutine for all the times it was called. Try using InvokeRepeatingGarren Fitzenreiter

1 Answers

0
votes

Your coroutine functions is working properly. The problem is that you are calling it from the Update function and it's being called many times in a second. You can use a boolean variable to check if the coroutine function is running. If it is running, don't attack or start new coroutine. If it is not, then you can start coroutine.

At the end of the coroutine function set that variable to false. There other ways to do this but this seems to be the easiest way.

bool isAttackingPlayer = false;
IEnumerator HarmPlayer()
{
    Debug.Log("Inside Harm Player");
    yield return new WaitForSeconds(5);
    Debug.Log("Player Health is the issue");
    isAttackingPlayer = false; //Done attacking. Set to false
}

void Update()
{

    transform.LookAt(target);
    float step = speed * Time.deltaTime;
    distance = (transform.position - target.position).magnitude;
    if (distance < 3.5)
    {
        if (isAttackingPlayer == false)
        {
            isAttackingPlayer = true; //Is attacking to true
            animator.SetFloat("Attack", 0.2f);
            StartCoroutine("HarmPlayer");
        }
    }
}