using UnityEngine; public class ArrayDeletionExample : MonoBehaviour { void Start() { string[] fruits = new string[] { "Apple", "Banana", "Orange" }; // Bananaを削除したいが、要素の詰め直しが難しい } }
using System.Collections.Generic; using UnityEngine; public class ListDeletionExample : MonoBehaviour { void Start() { List<string> fruits = new List<string> { "Apple", "Banana", "Orange" }; fruits.Remove("Banana"); foreach (string fruit in fruits) { Debug.Log("Fruit: " + fruit); } } }
List では要素の削除が簡単かつ安全に行えます。
// 配列の宣言と初期化 int[] scores = new int[3] { 100, 200, 300 }; // Listの宣言と初期化 List<int> scoreList = new (){ 100, 200, 300 }; scoreList.Add(400); // 要素の追加 scoreList.RemoveAt(0); // 要素の削除
// 配列の場合 string[] array = new string[3]; // 新しい要素を追加するには要素数を変更する必要がある // Listの場合 List<string> list = new List<string>(); // 新しい要素を追加する際、サイズの変更は不要
// 配列の場合 string[] array = new string[] { "Apple", "Banana", "Orange" }; // 要素を削除して空きを管理するのが難しい // Listの場合 List<string> list = new List<string> { "Apple", "Banana", "Orange" }; list.Remove("Banana"); // 要素を削除しても自動的に詰められる
using System.Collections.Generic; using UnityEngine; public class PlayerInventory : MonoBehaviour { List<string> items = new List<string>(); void Start() { // アイテムの追加 items.Add("Sword"); items.Add("Shield"); items.Add("Potion"); // アイテムの表示 foreach (string item in items) { Debug.Log("Player has: " + item); } } }
using System.Collections.Generic; using UnityEngine; public class EnemySpawner : MonoBehaviour { public GameObject enemyPrefab; List<Transform> spawnPoints = new List<Transform>(); void Start() { // スポーンポイントの取得 foreach (Transform spawnPoint in transform) { spawnPoints.Add(spawnPoint); } // 敵の出現 foreach (Transform spawnPoint in spawnPoints) { Instantiate(enemyPrefab, spawnPoint.position, Quaternion.identity); } } }
using System.Collections.Generic; using UnityEngine; public class ScoreManager : MonoBehaviour { List<int> scoreHistory = new List<int>(); void AddScore(int score) { scoreHistory.Add(score); } void DisplayScoreHistory() { for (int i = 0; i < scoreHistory.Count; i++) { Debug.Log("Score #" + (i + 1) + ": " + scoreHistory[i]); } } }