簡體   English   中英

如何在 Unity 3D 中使用 goto 屬性?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM