[原创Unity基础—C#中Dispose和 Finalize
C#资源回收和IDisposable接口的使用

IDisposable 和 Finalize 皆是为了方便管理非 C# 管理下的"垃圾回收"

那Entity在C#中应该如何实现呢?

Entity.cs

public abstract class Entity : IDisposable {

	private bool disposed = false;

#if UnityEditor环境下
    public UnityEngine.GameObject GameObject { get; set; }
#endif
	
	
	//构造函数
    public Entity() {
#if UnityEditor环境下
            GameObject = new UnityEngine.GameObject(GetType().Name);
            UnityEngine.GameObject.DontDestroyOnLoad(GameObject);
            var view = GameObject.AddComponent<ComponentView>();
            view.Type = GameObject.name;
            view.Component = this;
#endif
        }	

    //GC自动调用
    ~Entity() { 
    	Dispose(false); 
    }

	//销毁
    public virtual void OnDestroy() {
    		Dispose(false); 
    }

    /// <summary>执行与释放或重置非托管资源关联的应用程序定义的任务。</summary>
    public void Dispose() {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    private void Dispose(bool disposing) {
        if (!disposed) {
            if (disposing) {
                DisposeManaged();
            }
            DisposeUnmanaged();
        }
        disposed = true;
#if UnityEditor环境下
            UnityEngine.GameObject.DestroyImmediate(GameObject);
#endif
    }
    protected abstract void DisposeManaged();//释放托管资源
    protected virtual void DisposeUnmanaged()//释放非托管资源
    {}
}

ComponentView.cs

public class ComponentView : MonoBehaviour {
    public string Type;
    public object Component { get; set; }
}
Logo

分享前沿Unity技术干货和开发经验,精彩的Unity活动和社区相关信息

更多推荐