今天发现代码走到一个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操作,因为这样会产生较大的性能消耗。