【发布时间】:2015-09-07 11:15:38
【问题描述】:
我有一个类实例化场景层次结构中的几个统一游戏对象。此类实现 IDisposable。我应该将这些游戏对象作为托管资源还是非托管资源来处理?
我正在关注Dispose pattern,那么我应该将 GameObject.Destroy(myGameObject) 之类的调用放在哪里?
谢谢
编辑: 好的,假设我想在该类超出范围时销毁该类实例化的游戏对象。那你会怎么做呢?
编辑 2: 我正在测试处置。我找到了一个解决方案。它不会自动工作,因为无法从不同的线程调用 GameObject.Destroy(myGameObject)。它将抛出一个错误 CompareBaseObjectsInternal。因此,当不再需要时,我调用 myClass.Dispose()。此外,我将 Unity GameObject 作为托管还是非托管处理似乎无关紧要。
myMain()
{
DisposeTestClass test = new DisposeTestClass();
//...
test.Dispose();
}
class DisposeTestClass : System.IDisposable
{
public GameObject uselessGameobject { get; private set; }
public DisposeTestClass()
{
uselessGameobject = new GameObject("Useless gameobject");
}
#region IDisposable
private bool _disposed;
~DisposeTestClass()
{
Debug.Log("~DisposeTestClass()");
this.Dispose(false);
}
public void Dispose()
{
Debug.Log("Dispose()");
this.Dispose(true);
System.GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Debug.Log("Dispose(bool)");
if(_disposed)
{
Debug.Log("Disposed. Return.");
return;
}
if(disposing)
{
Debug.Log("Disposing of managed resources...");
// clean up managed resources
/*
if(uselessGameobject != null)
{
GameObject.Destroy(uselessGameobject);
Debug.Log("Game object destroyed.");
}
else
{
Debug.Log("Game object is null.");
}*/
}
Debug.Log("Cleaning up unmanaged resources...");
// clean up unmanaged resources
if(uselessGameobject != null)
{
GameObject.Destroy(uselessGameobject);
Debug.Log("Game object destroyed.");
}
else
{
Debug.Log("Game object is null.");
}
// set the flag
Debug.Log("Setting the disposed flag.");
this._disposed = true;
}
#endregion
}
}
【问题讨论】:
标签: c# unity3d idisposable