Find time since a variable was changed

  • A+
Category:Languages

How would you find the time since a certain variable was changed? Take for example a boolean variable, how would you find the time since it was last changed? I want to use the boolean variable as a trigger (activating the trigger when it's true), but only after an exact, constant time (such as 0.5s) has passed since it was changed to true (it can only be changed from false to true).

Here is the code I have:

using System.Collections; using System.Collections.Generic; using UnityEngine;  public class hitRegistration : MonoBehaviour {      AudioSource hitSound;     private bool hitState = false;     // Use this for initialization     void Start()     {         hitSound = gameObject.GetComponent<AudioSource>();     }     void OnMouseOver()     {         Debug.Log("Mouse is over game object.");         if (Input.GetKey(KeyCode.X) && hitState == false)         {             hitSound.Play();             hitState = true;         }     }     private void OnMouseExit()     {         Debug.Log("Mouse is no longer over game object.");         if (hitState == true)         {             // sound clip gets cut if the cursor leaves before its finished.             Destroy(gameObject);         }     }      // Update is called once per frame     void Update()     {      } } 

"OnMouseOver()" Is simply a function that is called when the mouse is placed over the game object in question. I want to delay destroying the game object until a certain time has passed.

 


First off, as noted in a comment, you are probably trying to solve this problem the wrong way and you are probably asking an "XY" question -- a question where you are asking a question about a proposed bad solution instead of asking a question about the actual problem you face.

To answer the question you actually asked, for better or worse: there is no way to associate behaviours with reading or writing a variable in C#, but you can associate behaviours with a property:

private bool hitState; // The "backing store". private bool HitState  {   get    {     return hitState;   }   set   {     hitState = value;   } } 

You would then use HitState rather than hitState throughout the rest of your class.

Now you can add whatever logic you want that happens when the property is read or written:

private DateTime hitStateTime = default(DateTime); private bool hitState; // The "backing store". private bool HitState  {   get    {     return hitState;   }   set   {     hitState = value;     hitStateSet = DateTime.Now;   } } 

Now you know when it was set. And so on.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: