Reactivity for Morpeh ECS
using System;
using Scellecs.Morpeh;
using Scellecs.Morpeh.Systems;
using UnityEngine;
[Serializable] public struct HeroComponent : IComponent { }
[Serializable] public struct HeroDamagedMarker : IComponent { }
[Serializable] public struct HeroDeadMarker : IComponent { }
public class HealthBarSystem : UpdateSystem {
[SerializeField] private GameObject healthBarPrefab;
private SystemStateProcessor<HealthBarSystemStateComponent> heroProcessor;
public override void OnAwake() {
heroProcessor = World.Filter
.With<HeroComponent>()
.With<HeroDamagedMarker>()
.Without<HeroDeadMarker>()
.ToSystemStateProcessor(CreateHealthBarForHero, RemoveHealthBarForHero);
}
public override void Dispose() {
heroProcessor.Dispose();
}
public override void OnUpdate(float deltaTime) {
heroProcessor.Process();
}
// Called when an entity has been added to the Filter
private HealthBarSystemStateComponent CreateHealthBarForHero(Entity heroEntity) {
var healthBar = Instantiate(healthBarPrefab);
return new HealthBarSystemStateComponent {
healthBar = healthBar,
};
}
// Called when an entity has been removed from filter or has been destroyed
private void RemoveHealthBarForHero(ref HealthBarSystemStateComponent state) {
Destroy(state.healthBar);
}
[Serializable]
private struct HealthBarSystemStateComponent : ISystemStateComponent {
public GameObject healthBar;
}
}
Morpeh.SystemStateProcessor is MIT licensed.