【问题标题】:How do I decrease the number of times my void update() updates?如何减少我的 void update() 更新次数?
【发布时间】:2020-12-25 00:11:31
【问题描述】:

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

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

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

【问题讨论】:

标签: c# unity3d scripting


【解决方案1】:

我建议您查看 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();
    }
}

【讨论】:

【解决方案2】:

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

首先要直接回答您的问题,除了更改每秒帧数之外,您无法真正更改调用更新方法的时间。这并没有多大意义。

我建议您检查一下您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 2020-09-07
    • 1970-01-01
    • 2018-03-07
    • 2018-05-27
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多