新建一个脚本,将下面脚本挂载到父物体上
注意: 实测第一种初始化删除会快很多,而且没有Update()方法,只在初始化执行一次;第二种方法执行完之后在Update()里面还是会不停的执行判断逻辑
目录结构如下:
第一种方法:Start()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleteAllTest : MonoBehaviour {
// Use this for initialization
void Start () {
DeleteOldImage ();
}
// 初始化删除
void DeleteOldImage(){
for (int i = 0; i < transform.childCount; i++) {
Destroy (transform.GetChild (i).gameObject);
}
}
}
第二种方法:Update()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleteAllTest : MonoBehaviour {
// Update is called once per frame
void Update () {
for (int i = 0; i < transform.childCount; i++) {
Destroy (transform.GetChild (0).gameObject);
}
}
}
关于下面评论的测试:代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleteAllTest : MonoBehaviour
{
// Use this for initialization
void Start()
{
//DeleteOldImage ();
}
void Update()
{
for (int i = 0; i < transform.childCount; i++)
{
Destroy(transform.GetChild(0).gameObject);
Debug.Log("Destroy:" + transform.GetChild(0).gameObject.name);
}
}
// 初始化删除
void DeleteOldImage()
{
for (int i = 0; i < transform.childCount; i++)
{
Destroy(transform.GetChild(i).gameObject);
Debug.Log("Destroy:" + transform.GetChild(i).gameObject.name);
}
}
}
测试结果如下:(两种方法都能正常删除所有子物体)
运行前:
RunTime: