- Home /
Make method run when a variable like frame count increments
Is there a way to make a method happen when a variable like framecount, time, position, velocity, etc, increments without using update methods or coroutines?
Answer by MikeNewall · Apr 01, 2021 at 07:35 PM
Those are all examples of state that changes frequently over time. If you had an event that fired each time the frame count changed, or time advanced, or the player moved, you would have an excessive amount of events firing.
Polling is better to check for changes of this nature. Inside of update, or with a coroutine if you would like to check at a fixed interval.
You can store the state of the previous frame at the end of each update, and check to see if it changed during the next frame.
Answer by Llama_w_2Ls · Apr 01, 2021 at 07:37 PM
You could write your own custom class that takes in a float, for example a time or framecount, and runs a callback method whenever the value is set. Here's an example:
class Number
{
public delegate void Notify();
public event Notify ValueChanged;
float _value;
public float Value
{
get { return _value; }
set { _value = value; OnValueChanged(); }
}
public Number(float value)
{
_value = value;
}
public void OnValueChanged()
{
ValueChanged?.Invoke();
}
}
This is a class called 'Number'. It takes in a float as a constructor, and whenever its value is set, it will run its event callback method, as long as it isn't null. Here's how you would use it:
public class MyClass : MonoBehaviour
{
void Start()
{
Number num = new Number(0.2f);
// Will run this method whenever the value is set
num.ValueChanged += OnValueChanged;
num.Value = 0.3f;
Debug.Log(num.Value);
}
void OnValueChanged()
{
Debug.Log("Value was changed!");
}
}
Hope that helps. @codejackup