Unity中如何实现对象临时销毁?C# Destroy()反向操作问询
Unity临时隐藏与恢复对象实现方案
需求:当Player1的transform.position.x小于baraj的transform.position.x时,临时隐藏Player2;当Player1的X位置超过baraj的X位置时,恢复Player2显示,同时切换对应相机。
原脚本存在的问题
- 频繁调用
GameObject.Find():Update中每帧执行查找操作会严重损耗性能,且已通过public变量声明了对象引用,完全没必要重复查找 - 使用
Destroy():该方法会彻底销毁对象,无法再恢复显示,不符合临时隐藏的核心需求 - 重复条件判断:多次判断相同的位置逻辑,不仅冗余还可能触发冲突(比如同时执行销毁Player1和切换相机的操作)
修正后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class switchCameras2 : MonoBehaviour { public GameObject baraj; public GameObject CameraOne; public GameObject CameraTwo; public GameObject Player1; public GameObject Player2; // 记录当前状态,避免每帧重复执行相同操作 private bool isPlayer1PassedBaraj = false; void Start() { CameraOne.SetActive(true); CameraTwo.SetActive(false); // 初始化Player2状态:默认显示(可根据需求调整) Player2.SetActive(true); } void Update() { bool player1IsRightOfBaraj = Player1.transform.position.x > baraj.transform.position.x; // 仅当状态发生变化时执行操作,避免无效重复执行 if (player1IsRightOfBaraj != isPlayer1PassedBaraj) { isPlayer1PassedBaraj = player1IsRightOfBaraj; if (isPlayer1PassedBaraj) { // Player1超过baraj:切换相机2,显示Player2,隐藏Player1 CameraTwo.SetActive(true); CameraOne.SetActive(false); Player2.SetActive(true); Player1.SetActive(false); } else { // Player1回到baraj左侧:切换相机1,隐藏Player2,显示Player1 CameraOne.SetActive(true); CameraTwo.SetActive(false); Player2.SetActive(false); Player1.SetActive(true); } } } }
关键改动说明
- 移除
GameObject.Find():直接使用已声明的public对象引用,大幅提升运行性能 - 用
SetActive()替代Destroy():通过激活/禁用对象实现临时隐藏,后续可随时恢复对象显示 - 添加状态标记
isPlayer1PassedBaraj:仅当位置状态发生变化时才执行逻辑,避免每帧重复执行相同操作 - 整合逻辑:将同条件下的操作合并,避免逻辑冲突和冗余
内容的提问来源于stack exchange,提问作者user14633516
相关产品推荐
相关产品推荐

