0

I am having an issue in unity where my object will do a translation and then nothing else, I want a sequence of translations and rotations to occur but it only does the first translation in the code and wont stop, I tried using a separate function to execute the translation instead of the Update function but this didn't work either, please help.

void Update () 
{
    if (enemyHit == false)
    {
        //enemy moving
        transform.LookAt(TTarget);


    }
    else if (enemyHit == true)
    {
        Debug.Log (enemyHit);

        Evade();
    }
}

IEnumerator Wait(float duration)
{
    yield return new WaitForSeconds(duration);
}

void Evade()
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    Wait(2);
    transform.Rotate(0,90,0);



}
2
  • Depending on the value of enemyHit, you may be calling transform.LookAt once per frame, which would tend to overwrite any other rotations that you're trying to do. Commented Aug 9, 2016 at 16:56
  • Looking at your new question, it looks like my answer solved your problem. You can go ahead and accept my answer. Commented Aug 9, 2016 at 19:50

1 Answer 1

1

A coroutine function should not be called directly like a normal function. You must use StartCoroutine to call it.

void Evade()
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    StartCoroutine(Wait(2););
    transform.Rotate(0,90,0);
}

Even when you fix that, the rotae function will now be called but there will be no waiting for 2 seconds. That's because a normal function does not and will not wait for coroutine function to return if the coroutine function has yield return null or yield return new WaitForSomething.....

This is what you should do:

You call a coroutine function when enemyHit is true. Inside the coroutine function, you translate, wait then rotate. I suggest you learn about coroutine and understand how it works before using it.

void Update()
{
    if (enemyHit == false)
    {
        //enemy moving
        transform.LookAt(TTarget);


    }
    else if (enemyHit == true)
    {
        Debug.Log(enemyHit);
        StartCoroutine(Evade(2));
    }
}

IEnumerator Evade(float duration)
{
    transform.Translate(Vector3.back * Time.deltaTime * movementSpeed);
    yield return new WaitForSeconds(duration);
    transform.Rotate(0, 90, 0);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.