场景中新建几个物体,运行后比较两次输出
using UnityEngine;
public class Test : MonoBehaviour
{
public GameObject[] gos;
private void Awake()
{
//使用Destroy
for (int i = gos.Length - 1; i >= 0; i--)
{
Destroy(gos[i]);
Debug.Log(gos[i]);
}
//使用DestroyImmediate
//for (int i = gos.Length - 1; i >= 0; i--)
//{
// DestroyImmediate(gos[i]);
// Debug.Log(gos[i]);
//}
}
}
使用Destroy销毁后仍然可以输出游戏物体,使用DestroyImmediate销毁后输出null
原因是DestroyImmediate是立即销毁(让GameObject置为Null),立即释放资源,做这个操作的时候,会消耗很多时间的,影响主线程运行
Destroy是异步销毁,是在当前帧结束后才会真正的销毁物体(让GameObject置为Null),一般在下一帧销毁,不会影响主线程的运行
官方推荐一般情况下使用Destroy