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
MediumMake Space take back the newest box.
- In
Update(), onInput.GetKeyDown(KeyCode.Space)and only whenboxes.Count > 0, getGameObject newest = boxes[boxes.Count - 1];. - Hide it with
newest.SetActive(false);and take it out withboxes.Remove(newest);. - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground