James Clarke
James Clarke

Reputation: 45

Unity 5 Object translation and rotation

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



}

Upvotes: 0

Views: 567

Answers (1)

Programmer
Programmer

Reputation: 125245

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

Upvotes: 1

Related Questions