【问题标题】:.SendMessage Crashes Unity C#.SendMessage 使 Unity C# 崩溃
【发布时间】:2016-12-02 15:16:50
【问题描述】:

我正在使用 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); 
    }
}

非常感谢任何帮助!

【问题讨论】:

  • 你在哪里/如何打电话给sendmyMessage

标签: c# unity3d sendmessage


【解决方案1】:

由于逻辑if(tiles[i].tag == "Tile") 这是你的答案,它冻结了。现在想象你碰撞的那个物体有标签“不是瓷砖”?那么循环永远不会结束。

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

【讨论】:

  • 我只是想为他简化他的代码,因为没有必要的 if 语句,但你的回答很完美
【解决方案2】:
while (i < tiles.Length)
{
    if(tiles[i].tag == "Tile")
    {
        //snip
    }     

    // else - loop forever?
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多