欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

entitas学习笔记二

程序员文章站 2024-03-25 23:51:10
...

创建脚本:Assets/Sources/1.HelloWorld/Systems/LogSystem.cs

using Entitas;
using System.Collections.Generic;
using UnityEngine;

namespace HelloWorldTest
{
    /// <summary>
    /// UseEntitasEntity:是通过 Generate 生成的
    /// </summary>
    public class LogSystem : ReactiveSystem<UseEntitasEntity>
    {
        public LogSystem(Contexts context) : base(context.useEntitas)
        {
        }

        /// <summary>
        /// 所以entitas的逻辑代码都在这里实现
        /// </summary>
        /// <param name="entities"></param>
        protected override void Execute(List<UseEntitasEntity> entities)
        {
            foreach (var entity in entities)
            {
                Debug.Log(entity.helloWorldTestLog.log_info);
            }
        }

        protected override bool Filter(UseEntitasEntity entity)
        {
            return entity.hasHelloWorldTestLog; //只有完成这个条件才能执行 Execute方法
        }

        protected override ICollector<UseEntitasEntity> GetTrigger(IContext<UseEntitasEntity> context)
        {
            return context.CreateCollector(UseEntitasMatcher.HelloWorldTestLog);
        }
    }
}

创建脚本:Assets/Sources/1.HelloWorld/Feature/UseEntitasFeature.cs

namespace HelloWorldTest
{
    public class UseEntitasFeature : Feature
    {
        public UseEntitasFeature(Contexts contexts) : base ("UseEntitasFeature")
        {
            Add(new LogSystem(contexts));
        }
    }
}

创建脚本:Assets/Sources/1.HelloWorld/Controller/GameController.cs

using Entitas;
using UnityEngine;

namespace HelloWorldTest
{
    public class GameController : MonoBehaviour
    {
        // Start is called before the first frame update
        private Systems systems;
        void Start()
        {
            systems = CreateSystem(Contexts.sharedInstance);
            systems.Initialize();
        }

        // Update is called once per frame
        void Update()
        {
            systems.Execute();
            systems.Cleanup();
        }

        private Systems CreateSystem(Contexts contexts)
        {
            return new Feature("UseEntitasFeaturexxxx")
                .Add(new UseEntitasFeature(contexts));
        }
    }
}

把GameController脚本挂在到场景的一个空物体中

创建脚本:Assets/Scripts/MouseInput.cs

using UnityEngine;

public class MouseInput : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Contexts.sharedInstance.useEntitas.CreateEntity().AddHelloWorldTestLog("HelloWorld");
        }
    }
}

也把 MouseInput脚本挂在场景中,运行游戏,鼠标点击。

相关标签: unity ECS