Get Time A Bool Has Been True

I have a public bool that I would like to track how long it has been set to “True”
Is there a way I can determine from an If statement how long the bool has been active for?

Something like:
if (somebool activeTime == ?)
Then do something

When you set the bool to true, you can also store the Time.time value at the same time. Time.time is the time in seconds since the game started, so when you need to check how long that bool had been true just compare it to the current Time.time value.

Hi This is a quick and dirty way ,

    private bool _Enabled;
    private float TimeFromBoolStart = 0;
    public bool yourBool
    {
        get
        {
            return _Enabled;
        }
        set
        {
            _Enabled = value;
            if (_Enabled)
            {
                TimeFromBoolStart = Time.realtimeSinceStartup;
            }
        }
    }

    public float GetTimeSinceBool()
    {
        if (yourBool)
        {
            return Time.realtimeSinceStartup - TimeFromBoolStart;
        }
        else
        {
            return 0;
        }
    }

Good Luck
Sfc

For some Reason my older post was Discarded

this is quick and dirty script

    private bool _Enabled;
    private float TimeFromBoolStart = 0;
    public bool yourBool
    {
        get
        {
            return _Enabled;
        }
        set
        {
            _Enabled = value;
            if (_Enabled)
            {
                TimeFromBoolStart = Time.realtimeSinceStartup;
            }
        }
    }

    public float GetTimeSinceBool()
    {
        if (yourBool)
        {
            return Time.realtimeSinceStartup - TimeFromBoolStart;
        }
        else
        {
            return 0;
        }
    }

Good luck
SFC

This is a great use-case for accessors! These can allow you to hook in other behaviour to when the variable has changed. In this case it would be something like this:

class MyClass 
{
    private bool _dontSetMeDirectly;
    private float setMeDirectlyChangeTime;
    public bool setMeDirectly
    {
        get { return _dontSetMeDirectly;}
        set 
        {
             if (value != _dontSetMeDirectly)
                 setMeDirectlyChangeTime = Time.time;

             _dontSetMeDirectly = value;
        }
    }

    void UsageExample()
    {
        setMeDirectly = true;
        Debug.Log("setMeDirectlyChangeTime: " + setMeDirectlyChangeTime);
     }
}

Simple don’t ever set the value of _dontSetMeDirectly outside of the accessors (get/set). And don’t change the setMeDirectlyChangeTime outside of the setter. Play around with accessors (getter/setters) and learn a bit about them, they are awesome.