user8886439
user8886439

Reputation:

How can I execute a statement when a boolean's value changes?

I am writing a script in Unity.

public class WhileOne : MonoBehaviour {

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

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

I want to enable another script from this script only when my boolean's value changes from false to true. I have already implemented the boolean's conditions and value assignments, I want to know how to check in an efficient manner when its value changes.

Thank you in advance.

Upvotes: 2

Views: 3241

Answers (1)

Programmer
Programmer

Reputation: 125245

Change the boolean variable from field to property and you will be able to detect when it changes in the set accessor.

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;
    }
}

Upvotes: 2

Related Questions