Menu
CoddyTech

가장 최근 항목 되돌리기

Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 85개 중 66번째.

목록에서 가장 최근에 추가한 항목은 마지막 항목이며, 인덱스는 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 플레이그라운드