Coroutine call stacks

419 views Asked by At

I wanted to use my coroutine to smoothly interpolate the position and rotation of multiple GameObjects with the script attached to them. When I start the coroutine, the smooth part works fine, but all of my Objects get moved to the same position, which was not what I intended. I want to understand why that is the case, and if there is a smart way to deal with it.

This is what my coroutine looks like:

    IEnumerator interpolate_Plate(Transform targ)
{
    float passedTime = 0;

    while (!transform.Equals(targ))
    {
        passedTime += Time.deltaTime;

        transform.position = Vector3.Lerp(transform.position, targ.position, passedTime);
        transform.rotation = Quaternion.Lerp(transform.rotation, targ.rotation,passedTime);
        yield return null;
    }

    yield break;
}

I was thinking about creating a mastercoroutine with a list in it and then call the smoothing part. Is the problem just, that the Reference of targ always gets reset for all coroutinecalls on the stack?

As requested by you the function that calls the coroutine:

public void move_Plate(Transform newPosition)
{
  StartCoroutine(interpolate_Plate(newPosition));
}
1

There are 1 answers

0
x3lq On

Okay so I found the solution, since Unity or C# works with pointers and so on the problem was. that I continously changed the transforms of all Objects, since I used the pointer to the transform of the next Object. But I moved that Object to so it all ended up on the last Object I moved.

How to prevent this:

I created a new class which stores my values so position and rotation of the old one. I store an Instance of that in my Class where I move the plates. I now changed from coroutine to the update method as suggested in the comments. With a flag I check if I should move the Object or not. Then I move it smoothly to the new Position.

Code:

private Trans MoveTo;
private bool move;

void Update()
{
    if (move)
    {
        float passedTime = 0;
        passedTime += Time.deltaTime;

        transform.position = Vector3.Lerp(transform.position, MoveTo.position, passedTime);
        transform.rotation = Quaternion.Lerp(transform.rotation, MoveTo.rotation, passedTime);
    }
}

Seems to work.