[英]How do I use goto attribute in Unity 3D?
这行得通吗? 这是在启动方法中,使用光子进行联网。 我正试图等到房间时间初始化。
Wait:
if (!PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("StartTime") )
{
goto Wait;
}
else
{
goto Continue;
}
Continue:
startTime = double.Parse(PhotonNetwork.CurrentRoom.CustomProperties["StartTime"].ToString());
一般来说,我会说完全避免使用goto
!
在几乎所有情况下,我认为任何其他解决方案都比goto
跳转更清洁、更易于阅读和维护。 它更像是过去的“遗物”。 在goto
的示例中,它可能是唯一有意义的用例.. 在switch-case
中或打破嵌套循环.. 但即使在那里你也可以找到其他(在我看来更好)的解决方案。
你的代码基本上等于写
while(!PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("StartTime")) { }
startTime = double.Parse(PhotonNetwork.CurrentRoom.CustomProperties["StartTime"].ToString());
最近,我希望你能看到一个巨大的问题:你有一个永无止境的while
循环!
while
内,条件永远不会改变Start
中运行它,因此整个 Unity 主线程被阻塞,直到该循环结束。 我不是 100% 确定,但 afaik PhotonNetwork
需要 Unity 主线程来分派接收到的事件 -> 你的情况可能永远不会成为真的。 您应该使用Coroutine
。 协程就像一个小的临时Update
方法。 它不是异步的,而是在Update
之后运行直到下一个yield
语句,因此仍然允许 Unity 主线程继续渲染并且不会冻结整个应用程序。
// Yes, if you make Start return IEnumerator
// then Unity automatically runs it as a Coroutine!
private IEnumerator Start ()
{
// https://docs.unity3d.com/ScriptReference/WaitUntil.html
// This basically does what it says: Wait until a condition is true
// In a Coroutine the yield basically tells Unity
// "pause" this routine, render this frame and continue from here in the next frame
yield return new WaitUntil(() => PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("StartTime"));
startTime = double.Parse(PhotonNetwork.CurrentRoom.CustomProperties["StartTime"].ToString());
....
}
甚至比在一个循环中检查每一帧实际上更好
所以像例如
bool isInitialzed;
private void Start ()
{
TryGetStartTime (PhotonNetwork.CurrentRoom.CustomProperties);
}
private void TryGetStartTime(Hashtable properties)
{
if(!properties.Contains("StartTime")) return;
startTime = double.Parse(properties["StartTime"].ToString());
isInitialzed = true;
}
public void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
TryGetStartTime (propertiesThatChanged);
}
而是让其他方法等到isInitialized
为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.