I want to create an attribute system for actors in my game where I need other game elements (other attributes, actors, etc.) to react whenever a certain attribute is changed.
To achieve this, I’ve tried to create an event which is called whenever the attribute is changed, so other game components which listen to this event can process it further.
Here is a sample of the custom class and the event delegate:
public delegate void AttributeChanged(ActorAttribute actorAttribute);
public class ActorAttribute
{
/*
properties here
*/
//constructors
public ActorAttribute(type somevalue)
{
/*
set properties here
*/
Init();
}
public ActorAttribute(type somevalue, type somevalue)
{
/*
set properties here
*/
Init();
}
//events
public event AttributeChanged OnAttributeChanged;
//functions
public void Init()
{
Update();
}
public void ChangeSomeValue(type somevalue)
{
//change a property to some value
Update();
}
public void Update()
{
//update properties
OnAttributeChanged(this);
}
}
Every actor creates a list of set attributes using this class in a loop when it’s created.
Now whenever an instance of this class is created it throws an error “NullReferenceException: Object reference not set to an instance of an object” when OnAttributeChanged(this)
is called.
Without this line the attribute is created just fine so the problem seems to be the this
refference, but when I call any this.property
before the event call, it returns its value just fine leaving me wondering what can be wrong.