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

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.xdnf.cn/news/18707.html

相关文章:

  • 牛客面经2 京东社招-002
  • PyTorch框架之图像识别模型与训练策略
  • 25.深入对象
  • 寻找AI——高保真还原设计图生成App页面
  • 华为/思科/H3C/锐捷操作系统操作指南
  • 鸿蒙应用网络开发实战:HTTP、WebSocket、文件下载与网络检测全攻略
  • 微信小程序和uni-app面试问题总结
  • 网络模型深度解析:CNI、Pod通信与NetworkPolicy
  • Spring Boot 实时广播消息
  • Java集合(Collection、Map、转换)
  • git实战(7)git常用命令速查表
  • GitHub发布革命性工具:GitHub Spark,用自然语言打造全栈智能应用
  • 商品与股指类ETF期权买卖五档Tick分钟级历史行情数据分析
  • Node.js 和 Express 面试问题总结
  • 目标跟踪 YOLO11 单目标跟踪
  • Maven仓库与Maven私服架构
  • Spring Boot 实现 POJO 级联封装复杂属性
  • React Hooks UseRef的用法
  • 高速CANFD收发器ASM1042在割草机器人轮毂电机通信系统中的适配性研究
  • 终结系统裸奔:Debian老旧版本安全加固终极指南
  • 梯度下降(线性回归为例)
  • 总结:Maven多仓库多镜像源配置
  • 【KO】前端面试五
  • MySQL存储过程详解
  • 【8位数取中间4位数】2022-10-23
  • 利用Prometheus监控服务器相关数据
  • 本地文件夹即时变身 Web 服务器(文件服务器)
  • 01数据结构-归并排序和计数排序
  • 用 Ansible 优雅部署 Kubernetes 1.33.3(RedHat 10)
  • 文件相关操作的函数和文件操作