Is there any way to trigger an event if a variable from another scripts changes without calling it in update(). I would love to avoid calling everything in update. In my case I have a time/date variable and I was wondering if there is a way for other scripts to see if the time was changed without using Update(). Thank you, Hapciupalit
Ok course. This is one way you could do it, I wouldn't say its the best way as I'm no expert The script containing the variable you want to monitor; Code (CSharp): using UnityEngine; public class EventSender : MonoBehaviour { private float _myFloat = 0f; public event OnVariableChangeDelegate OnVariableChange; public delegate void OnVariableChangeDelegate(float newVal); public float MyFloat { get { return _myFloat; } set { if (_myFloat == value) return; _myFloat = value; if (OnVariableChange != null) OnVariableChange(_myFloat); } } } The script containing the code you wish to listen for changes in your variable; Code (CSharp): using UnityEngine; public class EventListener : MonoBehaviour { private EventSender _eventSender; void Start() { _eventSender = GameObject.FindObjectOfType<EventSender>(); _eventSender.OnVariableChange += VariableChangeHandler; } private void VariableChangeHandler(float newVal) { Debug.Log("Event Fired. MyFloat = " + newVal); } private void Update() { //For Testing if (Input.GetKeyDown(KeyCode.DownArrow)) { _eventSender.MyFloat -= 0.5f; } else if (Input.GetKeyDown(KeyCode.UpArrow)) { _eventSender.MyFloat += 0.5f; } } }
Thank you very much. This is just perfect. For me as long as it works ... I don't care if it's the best solution.
This looks pretty useful but I cant get worked that. Even when I use exact same code I do receive nothing, even no feedback and no error. its an old post but if you guys are still alive, can you please help me. thanks