- Home /
The question is answered, right answer was accepted
How to pass an instance of a custom class into an event within itself?
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.
Answer by Michal Rajnoha · Jul 22, 2014 at 03:16 PM
Well I actually found the answer in the meantime in this video Unity - Events
The error is caused by calling an event with no listeners. It's not that this
is null, but the event being null and checking for it being null before calling it fixes the problem.
Answer by theLittleSettler · Jul 22, 2014 at 01:56 PM
Its impossible for this to be null (let us hope!) so I suppose OnAttributeChanged is null.
Follow this Question
Related Questions
Custom Documentation for Monodevelop 1 Answer
Share Public Classes 1 Answer
custom event delegate - convertible error 3 Answers
Left 4 Dead-style Spawnpoints? 1 Answer
custom class serialization problem 1 Answer