InvokeRepeating() not working properly in C#

I have this script:

using UnityEngine;
using System.Collections;

public class LipidScript : MonoBehaviour {
	float myRandomValue;

	void Update () 
	{
		InvokeRepeating("RandomValue", 3.0f, 3.0f);
		
		transform.Rotate(Vector3.forward * Time.deltaTime * 80 * myRandomValue);
	}
	
	void RandomValue()
	{
		myRandomValue = Random.value * 2 - 1;
		Debug.Log(myRandomValue);
	}
}

which seems like it should return a new random value once every three seconds but after the waiting period of 3 seconds it fires continuously, once per frame (at least). Another strange thing is that it slows my framerate of this extremely simple program from several hundred fps down to 3 fps over 10 seconds or so…

Any ideas of what is not happening right here?

Thanks!

It is because you are calling InvokeRepeating from Update. So every frame you are creating another invoke repeating queue rather than calling it from start. The delay was the three seconds to fire, then next frame, the one you created on frame 2 fired and so on.

So, put the InvokeRepeating in the Start() to fix the problem.

And, by 10 seconds, you are “InvokeRepeating” once for the first call, you created it again for the second, and you are creating another at that time, so you are calling it multiple times every frame eventually to infinity times a frame (Supposing your computer was fast enough to not crash or freeze up :wink: )

1 Like

What peter said is correct, but pending your use I would recommend looking into coroutines instead of the incoke repeating.

Aha!

Thank you both!

InvokeRepeating is basically a coroutine. It just saves you from writing:

void Start () {
     UpdateRandomNum ();
}

IEnumerator UpdateRandomNum () {
     while (true) {
          //stuff
          yield return new WaitForSeconds(3);
     }
}

I’m quite well aware of what it does, which is why I said depending on use.