其他分享
首页 > 其他分享> > Entitas 入门

Entitas 入门

作者:互联网

####使用 Entitas 实现 Hello World!

Entitas的Github地址:传送门

下载后导入工程,点击Tools菜单栏打开设置:
设置主界面

实现 Hellow World 正常的代码:

public class NormalHellowWorld : MonoBehaviour
{
    public string message = "Hello World";
    void Start()
    {
        Debug.Log(this.message);
    }
}

问题:
1.未使用Monobehaviour继承下来的各种属性或方法。
2.数据和逻辑未分离,都卸载了一个类里。


使用ECS改进后:
1.先创建一个 LogComponent
Component 只包含数据,所以只需一个 message。

[Game] //通过Game上下文可找到此Component
public class LogComponent : IComponent
{
    public string message;
}

PS:每次写完Component都需要重新生成一边代码。

2.再创建一个 LogSystem
System 是处理 Component 的。

public class LogSystem : ReactiveSystem<GameEntity>//ReactiveSystem:只要Component的值一发生变化,其中的Execute就会执行
{
    public LogSystem(Contexts context) : base(context.game)
    {
    }
    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        //过滤获取存在LogComponent的Entity
        return context.CreateCollector(GameMatcher.HelloWorldLog);
    }
    protected override bool Filter(GameEntity entity)
    {
        //条件,若成功才执行
        return entity.hasHelloWorldLog;
    }
    protected override void Execute(List<GameEntity> entities)
    {
        //过滤剩下的Component统一执行
        foreach (GameEntity entity in entities)
        {
            Debug.Log(entity.helloWorldLog.message);
        }
    }
}

这样逻辑层的代码就OK了。

3.再创建一个 InitSystem
负责在Game上下文中添加一个带有LogComponent的Entity

public class InitSystem : IInitializeSystem
{
    private GameContext _gameContext;
    public InitSystem(Contexts contexts)
    {
        this._gameContext = contexts.game;
    }
    public void Initialize()
    {
        //在game上下文中创建一个Entity,添加一个LogComponent
        this._gameContext.CreateEntity().AddHelloWorldLog("Hello World !");
    }
}

这样实体对象也创建出来了。

4.再创建一个 AddGameSystems
需要把所有的系统添加到Game上下文中

public class AddGameSystems : Feature //Feature 负责执行各种System
{
    public AddGameSystems(Contexts contexts) : base("AddGameSystems")
    {
        this.Add(new LogSystem(contexts));
        this.Add(new InitSystem(contexts));
    }
}

Feature的作用是:编辑器内,场景中会生成一个System节点,可以查看当前创建的所有System以及其消耗的性能,并可以进行调试。
这样整个逻辑写完了。

5.最后创建一个 GameController
需要与Unity关联起来

public class GameController : MonoBehaviour
{
    //存放所有的系统
    private Systems _systems;

    void Start()
    {
        //创建系统集合,将所有系统添加进去
        this._systems = new Feature("Systems").Add(new AddGameSystems(Contexts.sharedInstance));
        //初始化,执行所有实现IInitialzeSystem的Initialize方法
        this._systems.Initialize();
    }

    void Update()
    {
        this._systems.Execute();
        this._systems.Cleanup();
    }
}

运行起来后就看到了输出:

并且在 Hierarchy 窗口看到了所有的 System 和 Component 和 Entity。

在Inspector窗口也能看到具体的实体对象,带有一个LogComponent

标签:入门,Entitas,创建,._,Component,class,LogComponent,public
来源: https://blog.csdn.net/qq_33064771/article/details/113840301