事情是这样的,在本人写一个需求时,需要根据实际情况调整子对象的数量,
本人编写脚本如下:
Debug.Log("开始有子对象:" + Parent.GetComponentsInChildren<Image>().Length + "个");
GameObject.Destroy(Parent.GetChild(0).gameObject);
Debug.Log("现在有子对象:"+Parent.GetComponentsInChildren<Image>().Length+"个");
但是运行结果却是这样:
我不信邪地写了个遍历,结果还真就把已经删除的子对象给打印出来了,如此阴魂不散搞得我慌了
我脑中闪过一个想法,于是我把删除后的打印全部写到协程中,让他们等待1秒后才打印,这时候奇迹发生了
private void ToDel()
{
Debug.Log("开始有子对象:" + Parent.GetComponentsInChildren<Image>().Length + "个");
GameObject.Destroy(Parent.GetChild(0).gameObject);
StartCoroutine(GetDdad());
//throw new NotImplementedException();
}
IEnumerator GetDdad() {
yield return new WaitForSeconds(0f);
Debug.Log("现在有子对象:" + Parent.GetComponentsInChildren<Image>().Length + "个");
foreach (Transform ss in Parent)
{
Debug.Log(ss.name);
}
}
打印出来的结果:
对于这种情况,我猜了一下原因,大概后续代码不会等待销毁完成就继续执行了,而在销毁后面使用协程,协程需要等待销毁执行完成后才进行执行。
我想法不一定对,但是方法是有效的。