Entitas 中的Event 新增一個分數控制

zsdeus133發表於2018-04-25

Event特性可以使得模擬層和檢視層完全解耦

目標: 使得點選一下滑鼠 增加一次分數 (基於Entitas的Written Tutorials的第一個Hello world)

Component

[Game, Unique, Event(true)]
public class ScoreComponent:IComponent {
    public int value;
}

System

public class ScoreSystem : ReactiveSystem<GameEntity>, IInitializeSystem
{
    readonly Contexts _contexts;

    public ScoreSystem(Contexts contexts):base(contexts.game)
    {
        _contexts = contexts;
    }

    /// <summary>
    /// 初始化
    /// </summary>
    public void Initialize()
    {
        _contexts.game.SetScore(0);
    }

    protected override void Execute(List<GameEntity> entities)
    {
        _contexts.game.ReplaceScore(_contexts.game.score.value + 1);
    }

    protected override bool Filter(GameEntity entity)
    {
        return entity.hasDebugMessage;
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.DebugMessage);
    }
}

在GameSystem裡新增生成的 Add(new GameEventSystems(contexts));

Monobehavior(啟動指令碼)

public class ScoreLabelController : MonoBehaviour, IScoreListener {

    public Text label;

    void Start () {
        // scoreEntity是單例
        Contexts.sharedInstance.game.scoreEntity.AddScoreListener(this);
    }

    public void OnScore(GameEntity entity, int value)
    {
        label.text = "Score: " + value;
    }
}

相關文章