【问题标题】:Running coroutine for lerping color运行协程来处理颜色
【发布时间】:2022-08-11 23:33:47
【问题描述】:

我有一个协程,我正在努力将颜色从白色变为红色。它有效,但它只发生一次,因为协程只运行一次。

我希望这种情况像乒乓球一样发生两到三次,而不需要多次运行协程(因为那是不可行的)。

它应该从白色变为红色,然后红色变为白色,最后再由白色变为红色。有没有办法在下面显示的协程中做到这一点?

bool changingColor = false;

void Start(){
 StartCoroutine(LerpColor(this.GetComponent<MeshRenderer>(), Color.white, Color.red, 0.5f));
}

IEnumerator LerpColor (MeshRenderer mesh, Color fromColor, Color toColor, float duration) {
        if (changingColor) {
            yield break;
        }
        changingColor = true;
        float counter = 0;

        while (counter < duration) {
            counter += Time.deltaTime;

            float colorTime = counter / duration;
            Debug.Log (colorTime);

            //Change color
            mesh.material.color = Color.Lerp (fromColor, toColor, counter / duration);
            //Wait for a frame
            yield return null;
        }
        changingColor = false;
    }
  • 您是否考虑过使用循环?
  • 我在代码中使用了一个while循环
  • 嗯,是的。但是你说你想多次这样做。什么事情多次发生?一个循环!
  • ofc,但正如你所见,我不希望它以相同的模式重复。我希望它从白色变为红色,从红色变为白色,然后再从白色变为红色。
  • 那么为什么不在转发器循环的每次迭代结束时交换fromColor 和toColor 呢?

标签: c# unity3d


【解决方案1】:

你不能做这样的事情吗?:

IEnumerator LerpColor (MeshRenderer mesh, Color fromColor, Color toColor, float duration, int repetitions) {
    if (changingColor) {
        yield break;
    }
    changingColor = true;
    for (int i = 0; i < repetitions; ++i) {
        float counter = 0;

        while (counter < duration) {
            counter += Time.deltaTime;

            float colorTime = counter / duration;
            Debug.Log (colorTime);

            //Change color
            mesh.material.color = Color.Lerp (fromColor, toColor, counter / duration);
            //Wait for a frame
            yield return null;
        }
        Color tmp = fromColor;
        fromColor = toColor;
        toColor = tmp;
    }
    changingColor = false;
}

并这样称呼它?:

StartCoroutine(LerpColor(this.GetComponent<MeshRenderer>(), Color.white, Color.red, 0.5f, 4));

或者,如果您想保持方法不变,也许您可​​以围绕它创建一个包装器:

IEnumerator LerpColorRepeater(MeshRenderer mesh, Color fromColor, Color toColor, float repetitionDuration, int repetitions) {
    for (int i = 0; i < repetitions; ++i)
    {
        IEnumerator lerpColorEnumerator = LerpColor(mesh, i % 2 == 0 ? fromColor : toColor, i % 2 == 0 ? toColor : fromColor, repetitionDuration, repetitions);
        while (lerpColorEnumerator.MoveNext())
        {
            yield return lerpColorEnumerator.Current;
        }
    }   
}

用法:

StartCoroutine(LerpColorRepeater(this.GetComponent<MeshRenderer>(), Color.white, Color.red, 0.5f, 4));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2011-02-07
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多