- Home /
how to run update every second
hi, i need my code to execute a function every 1 second, i have them placed in the update() function, however it is being called too frequently. What is a solution?
Answer by demize2010 · May 26, 2011 at 06:44 PM
Game coding 101 - Update() runs every frame regardless ;)
From the Start() function instead call
InvokeRepeating("YOUR FUNCTION NAME", 0, 1.0);
"Your function name " should be the function which has the code you want execution every 1sec see http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.InvokeRepeating.html
InvokeRepeating("YOUR FUNCTION NA$$anonymous$$E", 0, 1.0f); // need a float identifier for the third argument if it's a decimal
Answer by Topper_Harley · May 10, 2016 at 02:21 PM
You can try this simple way fo more precision than InvokeRepeating :
// Next update in second
private int nextUpdate=1;
// Update is called once per frame
void Update(){
// If the next update is reached
if(Time.time>=nextUpdate){
Debug.Log(Time.time+">="+nextUpdate);
// Change the next update (current second+1)
nextUpdate=Mathf.FloorToInt(Time.time)+1;
// Call your fonction
UpdateEverySecond();
}
}
// Update is called once per second
void UpdateEverySecond(){
// ...
}
Answer by tanyanzhi · Aug 03, 2015 at 12:20 AM
You can also try this:
int interval = 1;
float nextTime = 0;
// Update is called once per frame
void Update () {
if (Time.time >= nextTime) {
//do something here every interval seconds
nextTime += interval;
}
}
Your answer
Follow this Question
Related Questions
Using InvokeRepeating in the Update method? 2 Answers
InvokeRepeating not executing - recently updated unity 1 Answer
Prefab Instantiation 1 Answer