首页 > 解决方案 > 当布尔值更改时如何执行语句?

问题描述

我正在用 Unity 编写脚本。

public class WhileOne : MonoBehaviour {

    public GameObject char1, char2, charChanger;
    bool theTrue = false;

    void FixedUpdate () {
        if (ThingController.howManyTrues <= 0)
            theTrue = false;
        else
            theTrue = true;
    }
}

只有当我的布尔值从 false 变为 true 时,我才想从该脚本启用另一个脚本。我已经实现了布尔值的条件和赋值,我想知道当它的值发生变化时如何有效地检查。

先感谢您。

标签: c#unity3d

解决方案


将布尔变量从字段更改为属性,您将能够检测到它何时在set访问器中更改。

public class WhileOne : MonoBehaviour
{
    private bool _theTrue;
    public bool theTrue
    {
        get { return _theTrue; }
        set
        {
            //Check if the bloolen variable changes from false to true
            if (_theTrue == false && value == true)
            {
                // Do something
                Debug.Log("Boolean variable chaged from:" + _theTrue + " to: " + value);
            }
            //Update the boolean variable
            _theTrue = value;
        }
    }

    void Start()
    {
        theTrue = false;
    }
}

推荐阅读