UnityEngine.UnityException: get_gameObject can only be called from the main thread.

今天发现代码走到一个for循环里面,出不来了:

   Debug.Log(piece.index);
   Debug.Log(piece.visible);
   GameManager.instance.ChangePieceVisibleStatus(piece.index, piece.visible);
   Debug.Log(piece.index + "初始化完成");

界面只出现了前面两行的Log,for循环只走了一次,走到第三行就跳出来了。

下面是具体的函数实现方式,值得一提的是,这个函数是在服务器给客户端传送消息时,客户端做的处理,也就是说,这个操作是异步的,并不在Unity的主线程中进行

 public void ChangePieceVisibleStatus(int index, bool isVisible)
    {
        if (PositionConverter.FindPiecesByIndex(index).gameObject.GetComponent<MeshRenderer>() != null)
        {
            PositionConverter.FindPiecesByIndex(index).meshRenderer.enabled = isVisible;
        }
        else
        {
            Debug.LogError("Empty Piece's MeshRender");
        }
    }

利用throw catch之后,查到了问题的报错:

	Debug.Log(piece.index);
    Debug.Log(piece.visible);
    try
    {
        GameManager.instance.ChangePieceVisibleStatus(piece.index, piece.visible);
    }
    catch (System.Exception ex)
    {
        Debug.Log(ex.ToString());
        throw;
    }
    Debug.Log(piece.index + "初始化完成");
               

丢出的异常显示:
在这里插入图片描述
报错原因:GetComponent操作应该在Unity的主线程内进行,最好的方式是在每一个Piece上面挂的piece脚本上挂一个meshrenderer component,避免在Update里面进行GetComponent操作,因为这样会产生较大的性能消耗。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值