直接上測試結果殖侵,方便后面使用:
GameObject被銷毀時當前幀可以繼續(xù)使用屬性(gameObject,parent,transform等等)兔仰。
GameObject被銷毀的下一幀判定null是相等的但是物體類型還是GameObject。
特別注意GameObject被銷毀時當前幀 根據(jù)它的Parent獲取childCount時是包含銷毀的GameObject,所以這里計數(shù)不是想象的那樣,如果使用childCount則在Destory前將父子關系解除
場景內未運行截圖
image.png
Test.cs代碼
//=====================================================
// - FileName: Test
// - Description:
// - Author: wangguoqing
// - Email: wangguoqing@hehemj.com
// - Created: 2017/12/13 17:12:17
// - CLR version: 4.0.30319.42000
// - UserName: Wang
// - (C) Copyright 2008 - 2015, hehehuyu,Inc.
// - All Rights Reserved.
//======================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Text;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Test : MonoBehaviour {
public GameObject obj;
void Start()
{
StartCoroutine(DestroyObj(obj));
}
IEnumerator DestroyObj(GameObject go)
{
Debug.Log("StartCoroutine");
Destroy(go);
Debug.Log("go:::" + go);
Debug.Log("go transform::1:::" + go.transform);
Debug.Log("type::1::"+ go.GetType().FullName);
//go = null;
yield return new WaitForEndOfFrame();
if (go == null)
{
Debug.Log("null===1");
}
if(go is GameObject)
{
Debug.Log("type::2::" + go.GetType().FullName);
}
Destroy(go);
if (go == null)
{
Debug.Log("null===2");
}
Debug.Log("go transform::2:::" + go.transform);//這里是77行
Destroy(go);
yield break;
}
}
運行結果
image.png
將go=null這行代碼注釋放開后的運行結果:
image.png
根據(jù)結果說明:
1. gameObject在第一次Destroy后名沒有立即被刪除,當前幀可以繼續(xù)使用溅话;相關屬性例如transform還可以用;在獲取它Parent的所有物體時是能讀到該gameObject屬性的歌焦,并且Parent讀取childCount是包含該gameObject計數(shù)的.
2. gameObject在第一次Destroy后的下一幀再使用時屬性讀取失敗飞几,應為Destroy的那一幀最終gameObject被銷毀,然后go變量為null(這里的null并不是C#真正的null独撇,因為go.transform報錯信息有說明)屑墨,但是Destroy(go)是不報錯的,