Unity 删除所有子物体

本文对比了两种在Unity中批量删除父物体下所有子物体的方法:一种是在Start()方法中调用,仅初始化时执行一次;另一种是在Update()方法中循环执行,每帧都会尝试删除。测试结果显示两者均能有效删除所有子物体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个脚本,将下面脚本挂载到父物体上

注意: 实测第一种初始化删除会快很多,而且没有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: 

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值