.SendMessage 使 Unity C# 崩溃

.SendMessage Crashes Unity C#

我正在使用 OverlapSphere 检测对象特定半径内的所有碰撞器。然后我过滤掉一些我不关心的。对于剩下的几个,我尝试向这些对象发送消息以更新它们的渲染颜色。每当它发送消息时,unity 就会冻结。我试图做一些研究,我能找到的最好的事情是无限循环可以冻结它。但我看不到这方面的潜力。这是代码:

要发送消息的对象:

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); 
    }
}

非常感谢任何帮助!

while (i < tiles.Length)
{
    if(tiles[i].tag == "Tile")
    {
        //snip
    }     

    // else - loop forever?
}

这是你的问题。如果标签 != "Tile" 那么你永远不会增加 i.

逻辑卡住了if(tiles[i].tag == "Tile")这是你的答案。现在想象一下,您碰撞的那个物体有标签 "not a tile"?然后循环永远不会结束。

foreach(var tile in tiles) {
    if (tile.tag == "Tile") {
        tiles[i].SendMessage("Highlight", status);
    }
}