Creating custom events
In this document we will discuss how to create a new strawberry event and how to use it.
Creating the event class:
All the events in Strawberry's Event System should implement IStrawberryEvent interface. It only has one member that you need to override, which is EventCallTime property. This will show the time when your event will be called.
See more on Event call times here
The default value of this property is EventCallTime.OnUpdate
public enum PlayerActions
{
MoveLeft,
MoveRight,
Jump,
Shoot
}
public struct PlayerInputEvent : IStrawberryEvent
{
public PlayerInputComponent Caller;
public PlayerActions Action;
}
This is the event object we are going to use. We are going to create a component which listens to keyboard input and fires an event which other components can listen to and do actions based on that.
.
.
.
public class PlayerInputComponent : BaseComponent
{
.
.
.
public override void OnUpdate()
{
base.OnUpdate();
if (GameContext.InputManager.Keyboard.IsKeyDown(Keys.Left))
{
EventManager.Invoke<PlayerInputEvent>(this, new PlayerInputEvent()
{
Caller = this,
Action = PlayerActions.MoveLeft
});
}
// And other conditions for other events.
}
}
As you can see in the code above we are listening to keyboard input and firing an event when a key is down. Now other components can subscribe to this event (PlayerInputEvent) like we did in this section.
Best Practices
We implemented our event as a struct. The reason for this is how C#'s GC works and creating a new class every frame (Update) causes Garbage Collection spikes which can lead to framerate hiccups. You can either cache your event objects or use a struct instead of a class.
See Also: