简体   繁体   中英

coroutine executes only once

I have a game where a car moves on a road, which has triggers along it. The purpose is to detect when the car enters those triggers and to do stuff depending on the trigger.

For the one I am having trouble, the camera is supposed to slowly move towards a second position which is behind and slightly above the car.

Here is what I tried:

    private void OnTriggerEnter(Collider other)
{


    if (other.attachedRigidbody.velocity.magnitude > 20.0f)
    {
        StartCoroutine(tst());
    }

}
IEnumerator tst()
{
    Camera cam = Camera.main;
    Vector3 newPosition = cam.gameObject.transform.GetChild(0).position;
    cam.transform.position = Vector3.MoveTowards(cam.transform.position, newPosition, camUnit);

    yield return new WaitForSeconds(3);

}

The camUnit is equal 1f but the problem is that it doesn't move to the correct location, as in if I just assign it the new position the camera is in a different perspective than the code above and it is instant and not slow to move to the next position.

What am I doing wrong? Thank you in advance.

Directly after your yield you are exiting the Coroutine. With what you describe, you actually want this in some form of loop, and yield after doing what you need to do. Then, after the function resumes you decide whether you go again and yield again, or continue on towards the exit of the Coroutine.

    bool isDone = false;
    while(!isDone)
    {
        Camera cam = Camera.main;
        Vector3 newPosition = cam.gameObject.transform.GetChild(0).position;
        cam.transform.position = Vector3.MoveTowards(cam.transform.position, newPosition, camUnit);

        yield return new WaitForSeconds(3);
        isDone = EnsureCameraLocation(); // Do whatever check you need to do to figure out if the camera is where you want it yet
    }

Note that the yield is inside the while statement which is what will make the Coroutine seamless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM