I’m trying to fire an event anytime the property is set, including when I change the property’s backing field in the Inspector. Is there anything I can do to achieve this? Should I be aware of any pitfalls with this approach?
public static event Action<State> GameStateChanged;
[SerializeField] private State _state;
public State State
{
get
{
return _state;
}
set
{
_state = value;
GameStateChanged?.Invoke(_state);
}
}
I think the main pitfall is you’re relying on behavior right at this twilight of objects that go back and forth across the running / editing boundary, when stuff gets torn down and stood back up. I’m not sure what the rules on serializing static event fields are… that might be where things are going funny.
There is a step missing here. You are changing the backing field, not using the property setter when change something in the inspector. If you want this behavior I think the easiest way would be to write a custom inspector window that contains a field for you to input the new state and a button that when pressed sets the property to that value. That would cause any listeners to fire accordingly since you are setting the property instead of the backing field. You will likely need to make some consideration for if the editor is playing or not, but I am unsure of your specific use case so maybe not.
Edit: I realized I didn’t answer your first question. Yes, this is the expected behavior as far I understand this subject. The backing field itself never effects the property that references it, it is just a container for that value.
Ahhh, that is an interesting approach. I will have to experiment with that. I can’t immediately think of any issues using validate like that, but I’ll post any problems I come across with it. Clever thought.