Unity自定义框架--------MyFramework(一)

MyFramework(一)

一、介绍
这是一个纯的前端框架,适用于unity的C#开发,如今只是一个雏形,是根据ET框架中的思想经过他人(我是伸手党)的整理而形成的初版。

二、整体构思
项目分为两个文件夹:Framework和Module
1、Framework文件夹
(1)Kernel:框架的核心
思想:跟unity的思想一样:一切皆对象。
首先自己定义了一个Object类,这是所有类型的基类。

	/// <summary>
    /// Entity / Component base class
    /// </summary>
    public class Object : IDisposable
    {
        /// <summary>
        /// 唯一Id(当前环境)
        /// </summary>
        public long InstanceId { get; private set; }
		//用作资源的回收和管理
        private bool isFormPool;
        public bool IsFormPool
        {
            get
            {
                return this.isFormPool;
            }
            set
            {
                this.isFormPool = value;
                if (!isFormPool) return;
                if (InstanceId == 0) InstanceId = IdGenerater.GenerateInstanceId();
            }
        }

        public Object Parent { get; set; }
		//只有继承Object的类才能被获取-------------对返回的类进行限定
        public T GetParent<T>() where T : Object
        {
            return Parent as T;
        }

        public Object()
        {
          	//给每个继承Object的类生成唯一id
            this.InstanceId = IdGenerater.GenerateInstanceId();
        }

        public virtual void Dispose()
        {
            this.InstanceId = 0;
            if (this.isFormPool)
            {
                Game.ObjectPool.Recycle(this);
            }
        }

        public bool IsDisposed
        {
            get
            {
                return this.InstanceId == 0;
            }
        }
    }

Entity.cs--------实体类,相当于Unity中的GameObject,一个实体上可以挂载许多个Component。

	/// <summary>
    /// 所有实体基类
    /// </summary>
    public class Entity : Object
    {
        public long Id { get; set; }

        private Dictionary<Type, Component> components = new Dictionary<Type, Component>();

        public Entity()
        {
            Id = InstanceId;
        }
		
		// 约束构造函数
        public virtual K AddComponent<K>() where K : Component, new()
        {
            Type type = typeof(K);
            if (this.components.ContainsKey(type))
            {
                throw new Exception($"Component already exist, id: {this.Id}, component: {typeof(K).Name}");
            }

            K component = ObjectFactory.CreateWithParent<K>(this, this.IsFormPool);

            this.components.Add(type, component);

            return component;
        }
        //获取挂载到Entity上的组件
         public virtual K GetComponent<K>() where K : Component
        {
            Type type = typeof(K);
            if (this.components.TryGetValue(type, out Component com))
            {
                return com as K;
            }
            Log.Error($"类型不存在:{type}");
            return null;
        }
        //移除组件
        public virtual void RemoveComponent<T>() where T : Component
        {
            if (IsDisposed) return;

            Type type = typeof(T);
            Component component;
            if (!this.components.TryGetValue(type, out component))
            {
                return;
            }

            components.Remove(type);

            component.Dispose();
        }
   }

Component.cs-------------所有组件的基类

	/// <summary>
    /// 所有逻辑组件基类
    /// </summary>
    public class Component : Object
    {

        public override void Dispose()
        {
            if (IsDisposed) return;

            Game.System.RemoveSystem(this);

            base.Dispose();
        }
    }

ObjectPool.cs------------对象池,用于管理所有的object对象

public class ObjectPool : Object
    {
        private readonly Dictionary<Type, Queue<Object>> objects = new Dictionary<Type, Queue<Object>>();

        public Object Fetch(Type type)
        {
            Object obj;

            if (!this.objects.TryGetValue(type, out Queue<Object> queue))
            {
                obj = (Object)Activator.CreateInstance(type);
            }
            else
            {
                if (queue.Count == 0)
                    obj = (Object)Activator.CreateInstance(type);
                else
                {
                    obj = queue.Dequeue();
                    Log.DebugPurple($"Fetch:{obj.GetType()}");
                }
            }

            obj.IsFormPool = true;
            return obj;
        }

        public void Recycle(Object obj)
        {
            obj.Parent = this;
            Type type = obj.GetType();
            Queue<Object> queue;
            if (!this.objects.TryGetValue(type, out queue))
            {
                queue = new Queue<Object>();
                this.objects.Add(type, queue);
            }
            queue.Enqueue(obj);
            Log.DebugPurple($"Recycle:{obj.GetType()}");
        }
    }

System.cs------整个系统的核心,管理所有对象的生命周期,自己实现的一套生命周期,而不是直接使用Monobehaior中生命周期。

/// <summary>
    /// 所有对象生命周期管理
    /// </summary>
    public sealed class System
    {
        private readonly MultiMap<Type, Type> types = new MultiMap<Type, Type>();

        private readonly Dictionary<long, Object> objects = new Dictionary<long, Object>();

        private readonly Dictionary<long, IUpdate> updates = new Dictionary<long, IUpdate>();
        private readonly Dictionary<long, ILateUpdate> lateUpdates = new Dictionary<long, ILateUpdate>();

        private Queue<long> startEnter = new Queue<long>();

        private Queue<long> updateEnter = new Queue<long>();
        private Queue<long> updateExit = new Queue<long>();

        private Queue<long> lateUpdateEnter = new Queue<long>();
        private Queue<long> lateUpdateExit = new Queue<long>();
        
        public void AddSystem(Object obj)
        {
            long InstanceId = obj.InstanceId;
            this.objects.Add(InstanceId, obj);

            if (obj is IStart)
            {
                startEnter.Enqueue(InstanceId);
            }
            if (obj is IUpdate)
            {
                updateEnter.Enqueue(InstanceId);
            }
            if (obj is ILateUpdate)
            {
                lateUpdateEnter.Enqueue(InstanceId);
            }
        }
        
        public void RemoveSystem(Object obj)
        {
            long instanceId = obj.InstanceId;

            if (objects.ContainsKey(instanceId)) objects.Remove(instanceId);

            if (updates.ContainsKey(instanceId)) updateExit.Enqueue(obj.InstanceId);

            if (lateUpdates.ContainsKey(instanceId)) lateUpdateExit.Enqueue(instanceId);
        }
        
        public void AddTypes(Assembly assembly)
        {
            types.Clear();

            foreach (Type type in assembly.GetTypes())
            {
                object[] objects = type.GetCustomAttributes(typeof(BaseAttribute), false);
                if (objects.Length == 0) continue;

                BaseAttribute baseAttribute = (BaseAttribute)objects[0];
                this.types.Add(baseAttribute.AttributeType, type);
            }
        }
}    

整个核心架构就这些了,这个思想跟ECS很像(也可以说是仿照ECS写的),可以完全不继承MonoBehaivor,动态实例化Entity,然后在对应的Entity上挂载相应的组件来实现管理的,而且不同的Entity挂载相同的组件就可以获得该组件的所有功能,用起来非常方便。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值