parthshukla
parthshukla

Reputation: 13

How do I decrease the number of times my void update() updates?

I am currently working on a weather app, which uses an API that allows 500 requests a day. I realised that I run out of my daily requests within 5 seconds of running the app. That means my void update() is fetching the values 60 times a second (= frame rate). How do I decrease that to something like once every 15 seconds? Thank you so much in advance!

Currently my void update looks something like this

void Update()
    {
        StartCoroutine(GetAqiInfo());
    }

Upvotes: 0

Views: 407

Answers (2)

IndieGameDev
IndieGameDev

Reputation: 2974

How do I decrease the number of times my void update() updates?

First of all to answer your question directly, you can't really change the times the updates method gets called besides changing the frames per seconds. That wouldn't make a lot of sense tough.

I would advise you to rather check that your IEnumerator is working properly, because it seems that you call it each frame instead of calling it once again after it's done.

To fix that you can use the Coroutine type and check if it's currently running or not.

Coroutine current;

void Update() {
    if (current == null){
        current = StartCoroutine(GetAqiInfo());
    }
}

Now we can edit the Enumerator to set the Couroutine to false after it's done and after there has been a certain delay.

If you also want to make sure that there aren't more than 500 requests you could check that before entering your IEnumerator.

int requests = 0;

IEnumerator GetAqiInfo() 
{
    if (request >= 500){
        return;
    }

    // Get the Aqi Info and increase the request count by 1
    request++;
    
    yield return new WaitForSeconds(15f);

   current = null;
}

Coroutine Documentation

Upvotes: 1

OmerCD
OmerCD

Reputation: 46

I would suggest you to look into the InvokeRepeting. Link Here

Instead of Update method, you should create another method to be invoked every given amount of time.

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    public Rigidbody projectile;

    void Start()
    {
        InvokeRepeating("RepeatedAction", 2.0f, 0.3f);
    }

    void RepeatedAction()
    {
        GetAqiInfo();
    }
}

Upvotes: 1

Related Questions