首页 > 解决方案 > 尝试修改 RGB 颜色时 Unity 冻结

问题描述

我正在尝试随着时间的推移逐渐修改 Unity Renderer 组件的 Color32 RGB 值,但是每当我在 Unity 中玩游戏时,它只会冻结程序并且我必须关闭。我确信这是因为我试图修改它,但我不知道我错在哪里。任何帮助将不胜感激。谢谢你。

void degradeGradually(Renderer ren){
    float time = Time.time; 
    Color32 col;
    while(((Color32)ren.material.color).r > 89f){
        if (Time.time - time > .025f) {
            time = Time.time;
            col = new Color32 ((byte)(((Color32)ren.material.color).r - 1f), (byte)(((Color32)ren.material.color).g - 1f), (byte)(((Color32)ren.material.color).b - 1f), 255);
            ren.material.color = col; 
        }
    }
}

标签: c#unity3drenderergameobject

解决方案


这是因为while此方法中的循环永远不会终止,因此Update调用它的方法永远不会完成。这会冻结你的游戏。

一种可能的解决方案是将此方法转换为协程(文档的第一个示例与您的代码非常相似!)并将 areturn yield null放在您的 while 循环的末尾:

IEnumerator degradeGradually(Renderer ren){
    float time = Time.time; 
    Color32 col;
    while(((Color32)ren.material.color).r > 89f){
        if (Time.time - time > .025f) {
            time = Time.time;
            col = new Color32 ((byte)(((Color32)ren.material.color).r - 1f), (byte)(((Color32)ren.material.color).g - 1f), (byte)(((Color32)ren.material.color).b - 1f), 255);
            ren.material.color = col; 
        }

        yield return null;
    }
}

然后在你叫它的地方,

 // Instead of degradeGradually(r);
 StartCoroutine(degradeGradually(r));

并且如果你需要在降级发生后直接做一些事情,你可以将它添加到degradeGradually.

            ...
            ren.material.color = col; 
        }

        yield return null;
    }

    DoStuffAfterDegrade();
}

此外,颜色分量值的范围从0f到 ,1f因此您每次都希望将它们减小小于 1f 的值。如所写,您将在进入if语句的第一帧上淡出黑色。您可能还必须将组件夹在两者之间0f-1f如果 Unity 给您输入负数带来任何麻烦。


推荐阅读