Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
Unity - function behave unexpectedly inside a coroutine

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????

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!