如何减少 void update() 更新的次数?

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

我目前正在开发一个天气应用程序,它使用 API 每天允许 500 个请求。我意识到我 运行 在 运行 打开应用程序后的 5 秒内完成了我的日常请求。这意味着我的 void update() 每秒获取值 60 次(= 帧速率)。我如何将其减少到每 15 秒一次?提前致谢!

目前我的无效更新看起来像这样

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

我建议您查看 InvokeRepeting。 Link Here

您应该创建另一个每隔给定时间调用的方法,而不是 Update 方法。

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    public Rigidbody projectile;

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

    void RepeatedAction()
    {
        GetAqiInfo();
    }
}

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

首先直接回答你的问题,除了改变每秒的帧数之外,你不能真正改变调用更新方法的时间。这不会让很多人觉得很难。

我建议您检查一下您的 IEnumerator 是否正常工作,因为您似乎是在每一帧都调用它,而不是在完成后再次调用它。

要解决这个问题,您可以使用 Coroutine 类型并检查它当前是否 运行。

Coroutine current;

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

现在我们可以编辑 Enumerator 以在 Couroutine 完成并经过一定的延迟后将其设置为 false。

如果您还想确保不超过 500 个请求,您可以在输入 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