Unity - function behave unexpectedly inside a coroutine

Viewed 47

the function look like this:

private void Shrink(Animation anim)
{
    AnimationClip clip = new AnimationClip();
    clip.legacy = true;

    char[] c = { 'x', 'y', 'z' };
    float rot = Random.value * 360 - 180;
    Vector3 toPosition = transform.position + (Random.value * radius * 5 / 6 + radius / 6) * new Vector3(Mathf.Cos(rot), Mathf.Sin(rot));
    float scaleMul = Random.value / 4 + 1.0f / 2.0f;
    float duration = (transform.position - toPosition).magnitude / speed;
    for (int i = 0; i < 3; i++)
    {
        Keyframe[] keys;
        keys = new Keyframe[2];
        keys[0] = new Keyframe(0.0f, transform.position[i]);
        keys[1] = new Keyframe(duration, toPosition[i]);
        curve = new AnimationCurve(keys);
        clip.SetCurve("", typeof(Transform), "localPosition." + c[i], curve);
    }
    for (int i = 0; i < 3; i++)
    {
        Keyframe[] keys;
        keys = new Keyframe[2];
        keys[0] = new Keyframe(0.0f, transform.localScale[i]);
        keys[1] = new Keyframe(duration, transform.localScale[i] * scaleMul);
        curve = new AnimationCurve(keys);
        clip.SetCurve("", typeof(Transform), "localScale." + c[i], curve);
    }


    // now animate the GameObject
    anim.AddClip(clip, clip.name);
    anim.Play(clip.name);
}

all it does is that it sort of animate the shrinking of a border and moving it to some random location inside a radius. the function works fine if I call it on its own but I want the function to be called every x seconds so I wrote this coroutine:

IEnumerator ShrinkCR(float time)
{
    for (int i = 0; i < 3; i++)
    {
        yield return new WaitForSeconds(time);

        Shrink(anim);
    }
}

and simply called it inside update():

private void Update()
{
    StartCoroutine(ShrinkCR(10));
}

but when I do that the border goes crazy and instead going to some random location inside some radius it just accelerate to the right indefinitly. What did I do wrong????

1 Answers

Update is called every frame, so you are launching th corroutine 60 times per second approx. That is why you are getting that behaviour. Call it once wherever/whenever you need, not in the update.

Related