c# - 尝试修改 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;
}
}
}
解决方案
这是因为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 给您输入负数带来任何麻烦。
推荐阅读
- c# - 无论如何将多个api端点聚合到单个swagger文档
- oracle - Oracle:使用来自同一表的聚合值更新表中的值
- c++ - Values changing after adding object pointer to vector
- sql-server - 加入子查询与加入表 - 为什么加入表不正确?
- ssl - activemq-cpp c++客户端如何使用ssl url连接服务器
- javascript - 如何在铯相机上设置最小缩放(和锁定轴)
- java - 有没有办法重定向 WOPI 休息调用以读取共享点文件?
- react-native - 如何从获取的 API 在渲染部分创建组件?
- azure-devops - 用于逻辑应用和天蓝色功能的 CI/CD 管道模板
- jquery - Multiple instance of jquery and sending value to php via ajax