Hi there,
how to make a custom event that triggers when a variables value is changed.
thanks!
Hi there,
how to make a custom event that triggers when a variables value is changed.
thanks!
Using simple variables, the best you can do is constantly check in update whether or not is has changed:
private int m_MyVar = 0;
public int myVar = 0;
public delegate void OnVariableChangeDelegate(int newVal);
public event OnVariableChangeDelegate OnVariableChange;
private void Update()
{
if (myVar != m_MyVar && OnVariableChange != null)
{
m_MyVar = myVar;
OnVariableChange(myVar);
}
}
However, if you can use properties this is a little cleaner because you know when a variable is set:
private int m_MyVar = 0;
public int MyVar
{
get {return m_MyVar;}
set {
if (m_MyVar == value) return;
m_MyVar = value;
if (OnVariableChange != null)
OnVariableChange(m_MyVar);
}
}
public delegate void OnVariableChangeDelegate(int newVal);
public event OnVariableChangeDelegate OnVariableChange;
To subscribe and listen to either of these events:
private void Start()
{
componentWithEvent.OnVariableChange += VariableChangeHandler;
}
private void VariableChangeHandler(int newVal)
{
//do whatever
}
@Zwusel In the Inspector, there is “on value changed” for sliders on the UI
just have it call a function to tell all classes the user has changed the slider.