【问题标题】:Running a loop inside Update()在 Update() 中运行循环
【发布时间】:2019-04-30 10:46:21
【问题描述】:

我需要根据数组 (data_int[]) 中的值更改对象的比例,如果值增加,它应该增加,反之亦然。我尝试的代码可以做到这一点,但我只能可视化最终结果。但是,我需要可视化循环中的每一步。

void Update()
{
    if (MyFunctionCalled == false)
    {

        for (int i = 1; i < 25; i++)
        {
            if (data_int[i] > data_int[i - 1])
            {
                transform.localScale += new Vector3(0.01f, 0.01f, 0.01f);
            }
            else if (data_int[i] < data_int[i - 1])
            {
                transform.localScale += new Vector3(-0.01f, -0.01f, -0.01f);
            }

        }
        MyFunctionCalled = true;
   }
  }     
 }
}

【问题讨论】:

  • 可视化循环中的每一步是什么意思?

标签: c# visual-studio unity3d


【解决方案1】:

您可以使用Coroutine 函数来实现您的目标。

yield return new WaitForSeconds(.5f) 行将模拟等​​待 0.5 秒,然后再继续。 yield return nullyield return new WaitForEndOfFrame() 等也可用于延迟 Coroutine 的执行。可以在here 找到有关每个返回时间的更多信息。 This question on coroutines 也可能有用。

    void Start()
    {
        StartCoroutine(ScaleObject());
    }

    IEnumerator ScaleObject()
    {
        for (int i = 1; i < 25; i++)
        {
            if (data_int[i] > data_int[i - 1])
            {
                transform.localScale += new Vector3(0.01f, 0.01f, 0.01f);
            }
            else if (data_int[i] < data_int[i - 1])
            {
                transform.localScale += new Vector3(-0.01f, -0.01f, -0.01f);
            }
            yield return new WaitForSeconds(.5f);
        }
    }

【讨论】:

  • 协程在 Update() 中不好用,因为 Update 不能等待。
  • @SaadAnees 使用没有任何问题,因为它正在这里使用。 MyFunctionCalled 值已阻止它运行多次。
【解决方案2】:

整个循环在 1 帧内执行,你看不到一步一步的。您可以“模拟”方法Update之外的循环

例如:

// initialize your iterator
private int i = 1;

// I removed the checks on MyFunctionCalled because this may be irrelevant for your question
void Update()
{
    // use an if instead of a for
    if (i < 25)
    {
        if (data_int[i] > data_int[i - 1])
        {
            transform.localScale += new Vector3(0.01f, 0.01f, 0.01f);
        }
        else if (data_int[i] < data_int[i - 1])
        {
            transform.localScale += new Vector3(-0.01f, -0.01f, -0.01f);
        }
        // this is the end of the supposed loop. Increment i
        ++i;
    }
    // "reset" your iterator
    else
    {
        i = 1;
    }
}

【讨论】:

  • 谢谢它完美的工作。只需要指出“ i ”应该初始化为 1 因为我在第一次迭代中与 i-1 进行比较。
猜你喜欢
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多