Unity中删除不及时的问题
在 Unity 开发中,我们经常使用 Destroy
来销毁物体。不过需要注意的是,Destroy
并不会立刻移除对象,而是将其标记为“待删除”。Unity 会在当前帧结束时(即下一帧开始前)统一执行这些销毁操作,所以如果我们在一个方法里面如果需要执行删除后的逻辑,并且这个逻辑还和删除物体有关的话就会出现问题。
我们可以写一个简单的代码来验证,这里场景中我创建了一个滑动列表,并添加了一个按钮,当点击按钮的时候就会执行删除带代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Dleattext : MonoBehaviour
{public Transform target;public Button textbtn;void Start(){textbtn.onClick.AddListener(DelatAllchildren);}void DelatAllchildren(){Debug.Log("删除前的子物体数量:"+target.childCount);for (int i = target.childCount - 1; i >= 0; i--){Destroy(target.GetChild(i).gameObject);}Debug.Log("删除后的子物体数量:" + target.childCount);}
}
运行结果我们会发现两次打印的结果都是18
但是游戏中的物体已经删除了
如果你想删除物体的时候立即执行可以使用下面两种方法
第一种使用DestroyImmediate()来删除物体。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Dleattext : MonoBehaviour
{public Transform target;public Button textbtn;void Start(){textbtn.onClick.AddListener(DelatAllchildren);}void DelatAllchildren(){Debug.Log("删除前的子物体数量:"+target.childCount);for (int i = target.childCount - 1; i >= 0; i--){DestroyImmediate(target.GetChild(i).gameObject);}Debug.Log("删除后的子物体数量:" + target.childCount);}
}
第二种使用携程等待一帧过后执行
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Dleattext : MonoBehaviour
{public Transform target;public Button textbtn;void Start(){textbtn.onClick.AddListener(() => StartCoroutine(DelatAllchildren()));}IEnumerator DelatAllchildren(){Debug.Log("删除前的子物体数量:" + target.childCount);for (int i = target.childCount - 1; i >= 0; i--){Destroy(target.GetChild(i).gameObject);}yield return null;//等待一帧Debug.Log("删除后的子物体数量:" + target.childCount);}
}