Skip to content

codewriter-packages/Morpeh.SystemStateProcessor

Repository files navigation

Morpeh.SystemStateProcessor Github license Unity 2021.3 GitHub package.json version

Reactivity for Morpeh ECS

How to use?

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;
    }
}

License

Morpeh.SystemStateProcessor is MIT licensed.