我有這個類附加到一個PauseButton物件。
public class PauseButton : MonoBehaviour
{
public bool firstTimePause;
private bool checkIfPause;
public void Awake()
{
firstTimePause = false;
}
public virtual void PauseButtonAction()
{
StartCoroutine(PauseButtonCo());
}
protected virtual IEnumerator PauseButtonCo()
{
yield return null;
checkIfPause = GameObject.Find("SomeObject").GetComponent<GameManager>().Paused;
if (firstTimePause == false && this.gameObject.name == "ResumeBackground" && checkIfPause == true)
{
firstTimePause = true;
Debug.Log("This is getting printed");
}
}
}
然后我有另一個類試圖訪問firstTimePause變數PauseButton
public class StopWatchTimer : MonoBehaviour
{
public Text textTime;
private PauseButton pauseButtonScript;
public GameObject pauseButtonObject;
// Use this for initialization
void Start()
{
pauseButtonScript = pauseButtonObject.GetComponent<PauseButton>();
}
void Update()
{
pauseButtonScript = pauseButtonObject.GetComponent<PauseButton>();
Debug.Log(pauseButtonScript.firstTimePause); //this value is always false even if it was already set to true on PauseButton Class
if (pauseButtonScript.firstTimePause == true)
{
//do something
}
}
}
為什么firstTimePause即使我通過 Debug.Log 檢查它是否設定為 True,但我總是在變數上得到 False
如果我把課程改成這樣,它就可以作業了。
public class PauseButton : MonoBehaviour
{
public bool firstTimePause;
private bool checkIfPause;
public void Awake()
{
firstTimePause = false;
}
public virtual void PauseButtonAction()
{
StartCoroutine(PauseButtonCo());
}
protected virtual IEnumerator PauseButtonCo()
{
yield return null;
checkIfPause = GameObject.Find("SomeObject").GetComponent<GameManager>().Paused;
firstTimePause = true;
Debug.Log("This is getting printed");
}
}
這意味著該宣告有問題this.gameObject.name == "ResumeBackground" && checkIfPause == true。但是由于這兩種情況都在列印"This is getting printed",我很困惑為什么它不能按我的預期作業。
這是帶有 GameManager 的 SomeObject

uj5u.com熱心網友回復:
firstTimePause == false && this.gameObject.name == "ResumeBackground" && checkIfPause == true
{
...
Debug.Log("This is getting printed");
}
但是由于兩種情況都在列印“這正在列印”
為什么我總是在變數 firstTimePause 上得到 False
這正是你所期望的,不是嗎?如果firstTimePause始終為假,那么您希望上述條件始終為假。
uj5u.com熱心網友回復:
我終于弄明白了。顯然,我有 2 個附加腳本的物件。
第一個物件是我將變數設定為真/假的地方。并通過 Debug.Log 檢查表明它正確設定了真/假。
第二個物件是我檢查真/假的地方,它總是假的,因為它沒有被改變。我要感謝@Erik Overflow,它讓我想到了這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488912.html
上一篇:剛體在Unity中穿過物體
