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????
You might have intended it to be this way but I think the reason it is going crazy is that because you start the coroutine in the update function which causes a new coroutine to start once a frame. So after ten seconds your Shrink() function will be called approximately 600 times.
Instead call your coroutine only once in start or some later method and define in your for loop how often you want your shrink method called. This way the coroutine will only be started once and it should behave as expected.
Your answer
Follow this Question
Related Questions
function behave unexpectedly inside a coroutine. 1 Answer
I can not modify localscale while I'm playing because of the Animator. 1 Answer
How do I animate child object to move into horizontal layout group. 0 Answers
Moving GameObject a specific distance in the Z direction and back again - regardless of rotation 1 Answer
Moving enemy towards player while playing animation 0 Answers