在Update()中运行循环

问题描述 投票:0回答:2

我需要根据数组中的值(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
2个回答
1
投票

整个循环在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;
    }
}

2
投票

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

线路,yield return new WaitForSeconds(.5f)将模拟等待.5秒,然后继续。 yield return nullyield return new WaitForEndOfFrame()和其他人也可能被用来推迟执行Coroutine。有关何时可以找到这些返回的更多信息hereThis 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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.