簡體   English   中英

如何在兩個腳本中使用 bool 來決定是否調用函數?

[英]How can I use a bool in two scripts to decide if to call a function or not?

在 FixedUpdate() 的第一個腳本中,我調用了這個函數:

private void FixedUpdate()
        {
            RotateView();
        }

內部旋轉視圖:

public void RotateView()
        {
            gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);
        }

在第二個腳本中,我像這樣調用 RotateView:

Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView();

但是現在我想使用 RotateView 函數向腳本添加一個布爾值,以便我可以在第二個腳本中決定是否調用 FixedUpdate 中的 RotateView。

我想控制是否會在第二個腳本的 FixedUpdate 中調用 RotateView 或者更好地控制以下行:

gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);

是否執行取決於我在第二個腳本中設置的標志,例如:

Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView(false);

false 所以它不會使用該行:

gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);

true 會使用它。 如果從第一個腳本中的 FixedUpdate 內部調用 RotateView,則為 false/true。

有很多方法可以做到:

  • 您可以使用[SerializeField] OtherScript foo;通過檢查器將一個腳本分配給另一個腳本[SerializeField] OtherScript foo;
  • 您可以將 bool 設為 public 和static ,然后可以通過OtherScript.foo訪問它
  • 您可以使用多種方法之一來獲取腳本之一的Start()中的另一個組件,例如FindObjectByType()GetComponent<...>()GetComponentInChildren<...>() ,布爾可以然后是 public 或 public 但使用 { get; 私人訂制; 訪問器,或通過像GetFoo()這樣的公共函數提供
  • 對於非常罕見的 bool 檢查,例如初始加載設置,Unity 中還有PlayerPrefs類(但它通常會被放入另一個變量中)
  • 您甚至可能會發現共享 bool 方法是錯誤的,而您希望讓一個類處理另一個類的RotateView調用等。

這在一定程度上取決於您如何構建程序、類應該做什么、它們的作用域是什么等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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