Unity3D克隆对象销毁后仍留存于层级面板的解决方法
问题修复:Unity克隆对象销毁后仍留存于层级面板
我编写了一段代码,用于在对象靠近玩家原点时克隆它们,当对象越过原点时销毁它们。该脚本挂载在两个游戏对象上。运行游戏时,原始对象销毁后会从层级面板中消失,但克隆对象销毁后仅从游戏画面消失,仍留存于层级面板中,请问该如何修复这个问题?
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveTraffic : MonoBehaviour { private float vehicleSpeed = 8.0f; private Vector3 startPosition; private bool needsDuplicate = true; // Start is called before the first frame update void Start() { startPosition = transform.position; // force startPosition Z to be at the edge of the road; startPosition.z = 178.0f; } // Update is called once per frame void Update() { // Move the vehicle forward or backward transform.Translate(Vector3.forward * Time.deltaTime * vehicleSpeed); //create duplicates at certain points along the road, starting them back at startPosition. var pz = transform.position.z; if (needsDuplicate) { //if ((pz < 178f * .75 && pz > 178f * .7) || (pz < 178 * .5 && pz > 178f* .4)) if (pz < 178 * .5 && pz > 178f * .4) { Instantiate(this, startPosition, transform.rotation); needsDuplicate = false; } } else { //if ((pz < 178f * .7 && pz > 178f * .6) || (pz < 178 * .5 && pz > 178f * .6)) if (pz < 178 * .5 && pz > 178f * .6) { needsDuplicate = true; } } //Respawn and destroy when it gets to the end of the road. if (transform.position.z < -2) { //transform.position = new Vector3(transform.position.x, transform.position.y, restartZ); Instantiate(this, startPosition, transform.rotation); Destroy(this.gameObject); } } }
问题根源与修复方案
1. 核心问题:错误的克隆目标
你当前使用Instantiate(this, ...)克隆的是脚本组件,而非游戏对象本身。Unity会自动为克隆的脚本创建一个空GameObject并挂载该组件,这种方式可能导致对象销毁时,层级面板无法正确同步移除操作。
2. 次要问题:无效的条件判断
else分支中的if (pz < 178 * .5 && pz > 178f * .6)逻辑矛盾(数值范围无法同时满足),导致needsDuplicate永远无法重置为true,克隆逻辑会出现异常。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveTraffic : MonoBehaviour { private float vehicleSpeed = 8.0f; private Vector3 startPosition; private bool needsDuplicate = true; void Start() { startPosition = transform.position; startPosition.z = 178.0f; } void Update() { transform.Translate(Vector3.forward * Time.deltaTime * vehicleSpeed); var pz = transform.position.z; if (needsDuplicate) { if (pz < 178f * .5 && pz > 178f * .4) { // 改为克隆游戏对象本身,而非脚本组件 Instantiate(this.gameObject, startPosition, transform.rotation); needsDuplicate = false; } } else { // 修复条件范围矛盾问题,示例调整为合理的数值区间 if (pz < 178f * .6 && pz > 178f * .5) { needsDuplicate = true; } } if (transform.position.z < -2) { Instantiate(this.gameObject, startPosition, transform.rotation); Destroy(this.gameObject); } } }
修复说明
- 替换
Instantiate(this, ...)为Instantiate(this.gameObject, ...):直接克隆目标游戏对象,确保销毁时能正确从层级面板移除。 - 修正else分支的条件判断:调整为合理的数值范围,保证
needsDuplicate状态能正常重置,克隆逻辑可循环执行。
内容的提问来源于stack exchange,提问作者TecBrat
相关产品推荐
相关产品推荐

