Not very familiar with declaring and using events and received error,
Event must be of delegate type
Basically want to pass IMyInterface
as a dependency to another class where that class can subscribe to receive MyClassEvent
events and the event data is MyClass
.
public interface IMyInterface
{
event MyClass MyClassEvent;
}
public class Implementation: IMyInterface
{
event MyClass MyClassEvent;
public void OnSomethingHappened
{
MyClassEvent?.Invoke(); // pass MyClass to subscribers
}
}
public class AnotherClass(IMyInterface ...)
{
OnMyClassEvent(MyClass args)
{
// do something
}
}
Use "event" keyword with delegate type variable to declare an event. Use built-in delegate EventHandler or EventHandler<TEventArgs> for common events. The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.
The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.
Events in Unity are a special kind of multicast delegate and, generally speaking, they work in the same way as regular delegates. However, while delegates can be called by other scripts, event delegates can only be triggered from within their own class.
Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.
You need to declare the event correctly and define the event args:
public class MyClassEventArgs : EventArgs { }
public interface IMyInterface
{
event EventHandler<MyClassEventArgs> MyClassEvent;
}
public class Implementation : IMyInterface
{
public event EventHandler<MyClassEventArgs> MyClassEvent;
public void OnSomethingHappened()
{
MyClassEvent?.Invoke(this, new MyClassEventArgs());
}
}
And to subscribe to it:
var implementation = new Implementation();
implementation.MyClassEvent += MyClassEvent;
private void MyClassEvent(object sender, MyClassEventArgs e) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With