当前位置: 首页 > news >正文

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);}
}

http://www.dtcms.com/a/347518.html

相关文章:

  • DeepSeek-V3.1发布,预示下一代国产芯片即将发布,更新一小版本,跨出一大步
  • 深入理解3x3矩阵
  • Java—— 配置文件Properties
  • Spring Boot 实现 POJO 级联封装复杂属性
  • Redis学习笔记 ----- 缓存
  • 寻鲜之旅“咖”约深圳,容声冰箱引领“养鲜”新体验
  • 解决coze api使用coze.workflows.runs.create运行workflow返回400,但text为空
  • ⚡ Ranger 基础命令与功能详解
  • Talkie AI
  • 硬件笔记(27)---- 恒流源电路原理
  • 环境 (shell) 变量
  • QT-Mysql-查询语句-查询是否有表-表列名-查询记录
  • 力扣hot100:搜索二维矩阵与在排序数组中查找元素的第一个和最后一个位置(74,34)
  • ros 消息类型与查阅相关内容
  • XCVM1802-2MSEVSVA2197 XilinxAMD Versal Premium FPGA
  • 同步和异步、阻塞和非阻塞的再理解
  • JAVA核心基础篇-集合
  • 力扣(组合)
  • 如何解决 pyqt5 程序“长时间运行失效” 问题?
  • React学习(十一)
  • Windows 平台查看端口占用情况并终止进程
  • flink常见问题之非法配置异常
  • leetcode 852 山脉数组的顶峰索引
  • 讲点芯片验证中的统计覆盖率
  • 【URP】[平面阴影]原理与实现
  • 如何使用和优化SQL Server存储过程:全面指南
  • 论文阅读:arxiv 2025 Can You Trick the Grader? Adversarial Persuasion of LLM Judges
  • 【数据分享】地级市对外开放程度(2002-2021)-有缺失值
  • SpringBoot自动装配原理深度解析
  • 【LeetCode 热题 100】300. 最长递增子序列——(解法一)记忆化搜索