Unity中Instantiate无限循环生成克隆体问题求助
Unity 单实例药品重生问题修复
你的问题核心是错误操作了预制体本身,而非实例化出来的游戏对象,导致旧实例没被销毁,每次按E键都新增克隆体。
问题代码的关键错误:
RespawnMedicine里销毁的是Medicineprefab(预制体资源),而非之前生成的药品实例——预制体无法被销毁,旧实例会一直留在场景中spawnMedicine每次都用预制体生成新对象,没有跟踪当前实例,导致实例越积越多
修正后的代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Medicine : MonoBehaviour { // 移除自定义Transform结构体,避免和Unity内置组件命名冲突 public Vector2[] respawnLocations; public GameObject medicinePrefab; private GameObject currentMedicineInstance; // 跟踪当前生成的药品实例 void Start() { respawnLocations = new Vector2[3]; respawnLocations[0] = new Vector2(8.04f, 5.13f); respawnLocations[1] = new Vector2(-1.5f, 9.65f); respawnLocations[2] = new Vector2(-9.93f, 4.7f); SpawnMedicine(); } void Update() { if (Input.GetKeyDown(KeyCode.E)) { RespawnMedicine(); } } void RespawnMedicine() { // 销毁当前存在的药品实例 if (currentMedicineInstance != null) { Destroy(currentMedicineInstance); } SpawnMedicine(); } void SpawnMedicine() { int randomIndex = Random.Range(0, respawnLocations.Length); Vector2 spawnPosition = respawnLocations[randomIndex]; // 实例化对象并保存到跟踪变量中 currentMedicineInstance = Instantiate(medicinePrefab, spawnPosition, Quaternion.identity); } }
额外优化说明:
- 移除了自定义
Transform结构体,避免和Unity内置的Transform组件命名冲突 - 变量名改为小驼峰格式(
medicinePrefab),符合C#编码规范 - 简化了
Vector2的初始化写法
内容的提问来源于stack exchange,提问作者Woopy
相关产品推荐
相关产品推荐

