- Home /
Update scene every 5 minutes
I would like to update some objects in my scene every 5 minutes. I tried doing it from the start function with a while(true)
statement but the computer is going crazy and nothing gets played.
After reading a little about coroutines i changed the code. My code looks like :
void Update () {
if (Time.time > curent_time && sw){
sw = false;
UpdateMyScene(); //should i use `Invoke` with `0.0f` here ?
curent_time = Time.time + updateMinutes;
sw = true;
Debug.Log("New update at :" + Time.time + " Next update at : " + curent_time);
}
}
private IEnumerable UpdateMyScene(){
Debug.LogWarning("In UpdateMyScene");
[....]
}
On the console i only get messages like the one in the update. Why don't i get the message from the function I call ?
Thansk in advance !
Have you tried looking up timers for Unity and tried some of the many examples?
Answer by rhose · Jun 11, 2013 at 01:37 PM
void Start(){
StartCoroutine(UpdateMyScene());
}
private IEnumerator UpdateMyScene(){
while(true){
Debug.Log("Time is now : " + Time.time);
UnityStoreClient client = new UnityStoreClient(new BasicHttpBinding(), new EndpointAddress(Strings.webserviceUrl));
Item[] items = client.GetUnity3dItems();
for(int i=0;i<items.Length;i++){
GameObject curent = GameObject.Find(items[i].name);
if (curent != null){
ItemFieldValue[] values = items[i].item_field_values;
for(int j=0;j<values.Length;j++){
GameObject o = GameObject.Find(curent.name + "/" + values[j].field_details.name);
if (o != null){
if (values[j].field_details.type_id.Equals(Strings.colorType))
UpdateColor (values[j], o);
if (values[j].field_details.type_id.Equals(Strings.textureType))
UpdateTexture (values[j], o);
}
}
}
}
yield return new WaitForSeconds(Strings.updateInterval);
}
}
this is the answer to my problem. a nice guy from unity chat helped me. thanks alot unity helpers.
Answer by barker_s · Jun 11, 2013 at 12:11 PM
First of all, Start() fires only once at the beginning of your object's lifetime, so it's not a good idea to put any update code there. Putting while(true) in there is even worse, since you're never going to exit that method and it will hang in there indefinitely.
There's a different function where you can update your game objects and it's called... Update() :) .
Here's an example how you can do that:
public float timeInterval; // interval in seconds
float actualTime;
void Start()
{
timeInterval = 300.0f; // set interval for 5 minutes
actualTime = timeInterval; // set actual time left until next update
}
void Update()
{
actualTime -= Time.deltaTime; // subtract the time taken to render last frame
if(actualTime <= 0) // if time runs out, do your update
{
// INSERT YOUR UPDATE CODE HERE
actualTime = timeInterval; // reset the timer
}
}
I don't know if it's the right way to do that, but it should work all right.