Hi,
EDIT: ew grammar error in the title :< i cannot edit this sorry guys.
This is a utility class which i am currently using in my project. Its really useful for me as it allows me to use a reactive way to program systems and i guess it could be useful for others aswell.
so the code is here: Unity ECS EventManager · GitHub just put it into your project. It has a dependency on UniRx
So basically it is scheduling a piece of work automatically if an event happened. The nice thing is that this keeps the system order in mind: eg if system A is before system B, then if you have an event, which both systems react on, then system A will do the work before system B.
It is really easy to use:
- Instead of implementing SystemBase, JobComponentSystem etc, you implement EventJobSystem
- Instead of implementing OnCreate/OnUpdate, implement Create and Update
- implement protected override void RegisterEvents(ListenerManager listener). The ListenerManager provides you with some methods which lets you handle events:
listener.RegisterOnFlag<ThisIsASingletonEntity>("a log message", (theSingletonEntityData, inputDeps) =>
{
//you can schedule some jobs, which will execute ONLY! if a singleton of type ThisIsSingletonEntity exists
return new Job().Schedule(inputDeps);
//you can do some stuff based on the singleton data too
if(theSingletonEntityData.Value > 0){ /*etc*/ }
});
You can also give an obsevable which will schedule the work whenever a new value is coming in (eg every 2 seconds for example, or something triggered from outside the system)
listener.RegisterOnEvent("this method will trigger every two seconds", Observable.Interval(TimeSpan.FromSeconds(2)), (intervalTimer, inputDeps) => {
return Entity.ForEach(etc etc).Schedule(inputDeps);
}
There is also RegisterOnEventAndFlag which combines both (eg an observable pushed a value and a specific singleton exists
The order in which the events are worked on is this:
- Observable triggers will be processed first
- Flag based events will happen next (eg events where a specific singleton needs to exists)
- OnUpdate will happen last
It also registers the “correct” RequireForUpdate Types (each type of entity inside RegisterOnEvent, will trigger the processing of the system), but you can decide to provide your own via protected override ComponentType[ ] RunSystemWhen(). If you return null, the system will run always.
It is definitly not super performant, since everything is wrapped in multiple lambdas, but iam using this eventsystem with great success. It allows me to program in a reactive way, maybe it helps you too
Note that this code is not tested when you trigger observable events multiple times per frame. I use this system only when i have 1 event per frame at most.
It also has CreateSingleton Method, which lets you easily create a new Singleton entity Deletion is not included since there are some code gen bugs with this.