Menu
CoddyTech

정리하기

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

foreach가 목록을 순회하는 동안 목록에서 항목을 제거하면 스크립트가 InvalidOperationException과 함께 중단됩니다. 대신 for를 사용해 역순으로 반복하세요. 항목 i를 제거하면 그 뒤에 있는 항목만 이동하며, 반복문은 이미 그 항목들을 방문한 상태입니다.

for (int i = coins.Count - 1; i >= 0; i--)
{
    if (coins[i].transform.position.y > 20f)
    {
        Destroy(coins[i]);
        coins.RemoveAt(i);
    }
}
challenge icon

챌린지

중급

바닥 아래로 떨어지는 블록을 제거하세요.

  1. foreach를 for (int i = blocks.Count - 1; i >= 0; i--)로 바꾸고, 이전처럼 blocks[i]를 아래로 이동시키세요.
  2. 이동한 후 blocks[i].transform.position.y < -1f이면 Destroy(blocks[i]);를 호출한 다음 blocks.RemoveAt(i);를 호출하세요.

‘플레이’를 누르세요. Hierarchy에 블록이 몇 개보다 많이 남아 있지 않습니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float fallSpeed = 5f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer -= spawnEvery;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        foreach (GameObject block in blocks)
        {
            block.transform.position += Vector3.down * fallSpeed * Time.deltaTime;
        }
    }
}

Unity 스크립팅 기초의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드