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?
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
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(){
// ...
}
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;
}
}
int interval = 1;
void Update()
{
if (Time.time % interval == 0)
{
// Your call
}
}