我正在使用OverlapSphere来检测对象特定半径内的所有对撞机。然后,我过滤掉一些我不在乎的东西。对于其余的几个,我尝试向这些对象发送消息以更新其渲染颜色。每当它发送消息时,团结就会冻结。我试图做一些研究,发现的最好的事情就是无限循环可以冻结它。但是我看不到有这种潜力。这是代码:
发送消息的对象:
void sendmyMessage(bool status)
{
Collider[] tiles = Physics.OverlapSphere(gameObject.transform.position, 10);
int i = 0;
while (i < tiles.Length)
{
if(tiles[i].tag == "Tile")
{
//turn light on
if (status == true)
{
tiles[i].SendMessage("Highlight", true);
i++;
}
//turn light off
if (status == false)
{
tiles[i].SendMessage("Highlight", false);
i++;
}
}
}
}
对象接收消息:
void Highlight(bool status)
{
//turn light on
if(status == true)
{
gameObject.GetComponent<Renderer>().material.color = new Color(0, 0, 0);
}
//turn light off
if(status == false)
{
gameObject.GetComponent<Renderer>().material.color = new Color(1, 1, 1);
}
}
任何帮助深表感谢!
最佳答案
由于逻辑if(tiles[i].tag == "Tile")
而冻结,这是您的答案。现在想象一下,您与之碰撞的对象是否带有标签“ not tile”?然后循环永远不会结束。
foreach(var tile in tiles) {
if (tile.tag == "Tile") {
tiles[i].SendMessage("Highlight", status);
}
}
关于c# - .SendMessage使Unity C#崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935443/