using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text; namespace Engine.Component { /// 游戏组件基类 public class BaseComponent : MonoBehaviour { /// 组件是否被销毁 protected bool IsDestroy = false; /// 组件是否被释放 protected bool IsDispose = false; /// 是否为空闲状态 public bool IsReset = false; /// 初始化函数 public virtual void Awake() { CacheComponents(this); } /// 重置组件,清空组件对外的所用引用,如果需要组件重用,需要在缓存前调用次函数 public virtual void Reset() { IsReset = true; this.gameObject.SetActive(false); } /// 开始使用 public virtual void StartUse() { IsReset = false; this.gameObject.SetActive(true); } /// 获得gameObject对象 public virtual GameObject GetGameObject() { return this.gameObject; } /// 释放函数,调用此函数后组件不可再用 public virtual void Dispose() { //修改释放标记 IsDispose = true; //是否需要调用销毁 if (!IsDestroy) { Destroy(this); } } /// 组件被销毁时调用,Unity3D底层API自动触发 private void OnDestroy() { DelComponents(this); //修改销毁标记 IsDestroy = true; //是否需要调用释放函数 if (!IsDispose) { this.Dispose(); } } private string mComponentKey = string.Empty; /// 组件缓存键值 public string ComponentKey { get { if (mComponentKey == string.Empty) { mComponentKey = GetComponentKey (this.GetGameObject()); } return mComponentKey; } } public static Dictionary DictBaseComponents = new Dictionary(); /// 缓存特效 protected static void CacheComponents(BaseComponent baseComponents) { if (!DictBaseComponents.ContainsKey(baseComponents.ComponentKey)) { DictBaseComponents.Add(baseComponents.ComponentKey, baseComponents); } else { DictBaseComponents[baseComponents.ComponentKey] = baseComponents; } } /// 查找组件 public static BaseComponent FindComponents(GameObject componentObj) { string componentKey = GetComponentKey (componentObj); if (DictBaseComponents.ContainsKey(componentKey)) { return DictBaseComponents[componentKey]; } else { return null; } } /// 删除缓存 protected static void DelComponents(BaseComponent baseComponents) { if (!DictBaseComponents.ContainsKey(baseComponents.ComponentKey)) { DictBaseComponents.Remove(baseComponents.ComponentKey); } } /// 获取某个GameObject上某个组件的键值 protected static string GetComponentKey(GameObject componentObj) { //StringBuilder strBuillder = new StringBuilder (); //strBuillder.Append (componentObj.GetInstanceID()); //strBuillder.Append (componentType.ToString()); return componentObj.gameObject.GetInstanceID().ToString();//strBuillder.ToString (); } } }