Menu
CoddyTech

Take Back the Newest

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 66 of 85.

The newest item of a list is its last one, at index Count - 1. Take it out with Remove, and ask Count > 0 first: on an empty list there is no last item, and reading one stops the script with an ArgumentOutOfRangeException.

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

Removing an item from the list does not touch the object in the scene: hide or destroy it yourself.

challenge icon

Challenge

Medium

Make Space take back the newest box.

  1. In Update(), on Input.GetKeyDown(KeyCode.Space) and only when boxes.Count > 0, get GameObject newest = boxes[boxes.Count - 1];.
  2. Hide it with newest.SetActive(false); and take it out with boxes.Remove(newest);.
  3. Log "Boxes: " + boxes.Count.

Press Play, click three times, then press Space: the last box disappears. Then Check.

Try it yourself

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: hide the newest box and remove it from the list
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground