Invoke Invoking once?

Hello,

I’m having a weird issue with the invoke command. It seems that the delay on the invoke works once, then the materials just start randomizing per frame as if there was no delay. Is there something about invoke that I’m not getting?

Thanks!
Grimm

using UnityEngine;
using System.Collections;

public class SCRIPT_MaterialRandomizer : MonoBehaviour {
	
	public UnityEngine.Material Material_1;
	public UnityEngine.Material Material_2;
	public UnityEngine.Material Material_3;
	public UnityEngine.Material Material_4;
	public int ExecDelay = 1;
	
	public ArrayList MaterialArray = new ArrayList();
	
	// THIS ASSIGNS A RANDOM MATERIAL TO THE BLOCK FROM THE ARRAY OF MATERIALS
	void RandomizeMaterial() {
		int Rndm_MatID = Random.Range(0, MaterialArray.Count);
		
		renderer.material = MaterialArray[Rndm_MatID] as UnityEngine.Material;
	}
	
	// THIS DELAYS EXECUTION FOR (ExecDelay) SECONDS THEN CALLS THE MATERIAL RANDOMIZER FUNCTION
	void DelayUpdate() {
		RandomizeMaterial();
	}
	

	// Use this for initialization
	void Start () {
		MaterialArray.Add(Material_1);
		MaterialArray.Add(Material_2);
		MaterialArray.Add(Material_3);
		MaterialArray.Add(Material_4);
		
		RandomizeMaterial();
	}
	
	// Update is called once per frame
	void Update () {
		//StartCoroutine(DelayUpdate());
		//Invoke("DelayUpdate", 10);
		InvokeRepeating("DelayUpdate", 1, 10F);
	}
}

1 Answer

1

You call it every frame! So basically you start a new function each frame and each call gets delayed 10 sec. After the first 10 sec all those calls you’ve made will be executed, one each frame.

Calling InvokeRepeating every frame is even worse… you will end up with an infinite amount of calls since you add a new call each frame!

If you want DelayUpdate to run only every 10 sec just use InvokeRepeating one time in Start(). Once you’ve called it DelayUpdate will be called every 10 sec.