- Home /
How do i declare a non-static event?
I've asked (almost) this question before: http://answers.unity3d.com/questions/950815/how-do-i-declare-an-event-listener.html
I got some answers, the first one was to just make it static, which i went with and which worked up until now. Now i have a specific need for a per-instance event.
I got another answer there, from CHPedersen which explains how to do this non-statically, but frankly i just don't understand it. I cannot get it working. So can someone please explain this to me again and/or in more detail.
Here is what i have so far:
Declaring the event
public delegate void DestinationEventHandler();
public event DestinationEventHandler DestinationChanged;
Creating a listener to the event, using a reference (creature) to an instance of the class which contains the above code.
creature.DestinationChanged += new creature.DestinationEventHandler(ReadPath);
This second part does not compile. I don't understand why. The example in the linked page, the only difference i could understand was the inclusion of "EventArgs e" in the handler. I don't know what that is, and it won't compile if i try to use it. Is that necessary?
One other difference i noticed is: "buffer_OnDataProcessed;" in the example, i don't understand the use of an underscore there, and attempting to do the same for me doesn't compile either.
I'm stuck, pls help ;-;
Answer by Baste · May 15, 2015 at 10:14 AM
I'm not quite sure what you're trying to do with "new creature.DestinationEventHandler(ReadPath);"
If you want to add the ReadPath method to the creature's DestinationChanged callback, you do it like this:
creature.DestinationChanged += creature.ReadPath;
I find that using the classes Action and Func is more readable than delegates. They're predefined delegates that you can use - Action has no return values, while Func has one. In your case, you could replace this:
public delegate void DestinationEventHandler();
public event DestinationEventHandler DestinationChanged;
with this:
public Action DestinationChanged;
Your answer
Follow this Question
Related Questions
Notifying multiple enemies on player death 0 Answers
GameObject.Find breaks code with UnityEvent 2 Answers
Event Listener for Javascript? 0 Answers
How do i declare an event listener? 2 Answers
Passing sender object as an argument in AddListener method 1 Answer