Menu
CoddyTech

收回最新生成的对象

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 66 课,共 85 课。

列表中最新的项是最后一项,索引为 Count - 1。用 Remove 将它移除,并先检查 Count > 0:列表为空时没有最后一项,读取最后一项会导致脚本因 ArgumentOutOfRangeException 而停止。

if (coins.Count > 0)
{
    GameObject last = coins[coins.Count - 1];
    coins.Remove(last);
    Destroy(last);
}

从列表中移除一项不会影响场景中的对象:你需要自行隐藏或销毁它。

challenge icon

挑战

中等

按下 Space 键,移除最新的方块。

  1. 在 Update() 中,当按下 Input.GetKeyDown(KeyCode.Space) 且仅当 boxes.Count > 0 时,获取 GameObject newest = boxes[boxes.Count - 1];。
  2. 用 newest.SetActive(false); 隐藏它,并用 boxes.Remove(newest); 将它移除。
  3. 记录 "Boxes: " + boxes.Count。

按下“开始”,点击三次,然后按下 Space 键:最后一个方块会消失。然后点击“检查”。

亲手试试

using System.Collections.Generic;
using UnityEngine;

public class BoxStacker : MonoBehaviour
{
    public GameObject boxPrefab;
    List<GameObject> boxes = new List<GameObject>();

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 spot = transform.position + new Vector3(boxes.Count * 1.5f, 0, 0);
            GameObject box = Instantiate(boxPrefab, spot, Quaternion.identity);
            boxes.Add(box);
            Debug.Log("Boxes: " + boxes.Count);
        }

        // Space:隐藏最新的盒子,并将它从列表中移除
    }
}

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器