c# - .SendMessage使Unity C#崩溃

标签 c# unity3d sendmessage

我正在使用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/

相关文章:

c# - 着色器中的Unity相对方向

c# - 在 MacOS 上打开 Finder 窗口和访问硬件时遇到问题

c# - SendMessage 的正确声明是什么?如何转换我的代码以使用其参数?

c++ - SendMessage 与 PostMessage + WaitForSingleObject

c# - 在 asp.net mvc 中使用 @Html.TextArea

c# - 在 app.config 中增加后运行 WCF 测试客户端并收到 MaxReceivedMessageSize 错误

c# - 在 C# 中更改默认字体对话框

c# - 使用 Unity 在 C# 中发送 http 请求

c++ - 从另一个窗口上的控件获取文本时出现问题

c# - 判断运算是否会溢出?