Stazick 5
Stazick 5

Reputation: 21

Get notified when a variable changed

Is there any way to get when a variable has been changed? And if so, how can I achieve this?

Upvotes: 2

Views: 2607

Answers (2)

Lukas
Lukas

Reputation: 437

Just check in the Update void. I would argue that this is the easiest way to achieve what you want in Unity.

var varToCheckIfChanged; //This is the variable you want to know if it is still the same
var tempVar; //This variable stores the original value, and every time the varToCheckIfChanged changed, you update it.

//Gets called on Start of the scene
void Start
{
     tempVar = varToCheckIfChanged;
}

//Gets called every frame
void Update
{
    if(varToCheckIfChanged != tempVar)
    {
        Debug.Log("Variable changed!"); //Debug when the variable is updated
        var tempVar = varToCheckIfChanged;
    }

}

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

The "official" way to do it, is INotifyPropertyChanged. E.g. it is used by UI's (Windows Forms, WPF) to automatically refresh controls, when the data object they are bound to updates.

public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    ...
}

Then you can implement properties like this

private string _name;
public string Name
{
    get { return _name; }
    set {
        if (value != _name) {
            _name = value;
            OnPropertyChanged(nameof(Name));
        }
    }
}

You can use it like this:

var myObj = new MyClass();
myObj.PropertyChanged += MyObj_PropertyChanged;

myObj.Name = "new name";

// Clean up (e.g. in a `Dispose()` method)
myObj.PropertyChanged -= MyObj_PropertyChanged;

Assuming this event handler:

// Will be called whenever a property of `MyClass` is updated.
private void MyObj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    // Example
    if (e.PropertyName == nameof(MyClass.Name)) {
        var myObj = (MyClass)sender;
        //TODO: do something.
    }
}

Upvotes: 5

Related Questions