Unity中克隆对象存入数组及添加回退按钮删除最新克隆的问题咨询
问题根源
你原代码仅使用单个GameObject变量存储克隆引用,每次实例化新对象时都会覆盖上一个对象的引用,无法保存所有生成的克隆,因此无法实现回退操作。
优化方案
使用动态长度的List<GameObject>存储所有克隆引用,比固定长度的数组更适配动态增减对象的场景,实现逻辑如下:
- 首先在脚本顶部引入集合命名空间:
using System.Collections.Generic;
- 调整变量定义,删除原有
public GameObject clone;,替换为列表变量:
public List<GameObject> cloneList = new List<GameObject>();
- 修改实例化逻辑,生成克隆后将其加入列表:
if (touchField.Pressed == true) { GameObject clone = Instantiate(prefab, result, prefab.transform.rotation); clone.transform.parent = gameObject.transform; // 新增:把新生成的克隆加入列表 cloneList.Add(clone); }
- 新增回退方法,用于绑定按钮点击事件:
public void UndoLastSpawn() { // 列表存在元素时才执行回退 if(cloneList.Count > 0) { // 取最后生成的克隆对象 GameObject lastClone = cloneList[cloneList.Count - 1]; // 销毁对象 Destroy(lastClone); // 从列表中移除已销毁对象的引用 cloneList.RemoveAt(cloneList.Count - 1); } }
按钮绑定操作
在Unity编辑器中选中回退按钮,在Inspector面板找到Button组件的OnClick事件,点击+号,将挂载了TouchSpwan脚本的物体拖入事件槽,下拉选择TouchSpwan -> UndoLastSpawn即可。
完整修改后代码
using System.Collections.Generic; using UnityEngine; public class TouchSpwan : MonoBehaviour { public GameObject prefab; public Rigidbody rot; public Camera mainCamera; public FixedTouchField touchField; public float gridsize; public List<GameObject> cloneList = new List<GameObject>(); void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 touchPos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 9.8f)); touchPos.x = Mathf.Floor(touchPos.x / gridsize); touchPos.z = Mathf.Floor(touchPos.z / gridsize); Vector3 result = new Vector3((float)touchPos.x * gridsize, touchPos.y, (float)touchPos.z * gridsize); if (touchField.Pressed == true) { GameObject clone = Instantiate(prefab, result, prefab.transform.rotation); clone.transform.parent = gameObject.transform; cloneList.Add(clone); } } } public void UndoLastSpawn() { if(cloneList.Count > 0) { GameObject lastClone = cloneList[cloneList.Count - 1]; Destroy(lastClone); cloneList.RemoveAt(cloneList.Count - 1); } } }
内容的提问来源于stack exchange,提问作者broviv
相关产品推荐
相关产品推荐

