LoginSignup
5
2

More than 3 years have passed since last update.

UnityでListを使ってみよう

Posted at

今回はUnityでListを使ってみたいと思います。

Listは配列と近いイメージですが、
要素数を気にすることなく、要素の追加、削除など配列ではできない処理ができます。

動的に値を変更できるので「動的配列」とも言われます。
では早速見ていきましょう。

Listの定義

まずはListの定義からです。

例えば、int型の要素を格納するListを作りたい場合、以下の様に定義します。


List<int> list = new List<int>(); //int型のListを定義

配列では、定義時に長さを指定する必要がありますが、Listはその必要がありません。

Listは最初このように宣言し、後から要素の出し入れをします。

どの型を指定するかは、<>の中に記述します。

配列型も指定することができます。


List<int[]> list = new List<int[]>(); 

Listに要素を追加する

Listに要素を追加していく方法です。

Addメソッドを使う

シンプルに要素を1つずつ入れていく方法です。

List<int> list = new List<int>();

list.Add(10); 
list.Add(20);
list.Add(40);

AddRangeメソッドで配列の要素を入れる

配列の中身を全て追加することができます。

List<int> list = new List<int>();

int[] a = {10,20,340}; //int型配列

list.AddRange(a); 

Listの要素を取得

正しく値が追加できたか確認するために、Listの中身の取得します。

List<int> list = new List<int>();

list.Add(3);
list.Add(2);
list.Add(4);

int[] a = { 10, 20, 340 };
list.AddRange(a);

Debug.Log("Listの0番目の値は"+ list[0]); // 0番目の値は3
Debug.Log("Listの長さは" + list.Count); // 長さは6

list[0]とするとListの0番目の値を取得できます。これは配列と同じですね。

list.Countとすることで、要素数を取得できます。

またListの全ての要素を順番に取得したい場合は、ループ文を使えばできます。

for(int i = 0; i < list.Count; i++)
{
    Debug.Log(list[i]);
}

Listから要素を削除

Listから要素を削除するやり方についてです。

Removeメソッド

特定の要素をListから削除します。

List<int> list = new List<int>();

list.Add(3);
list.Add(10);
list.Add(4);

int[] a = { 10, 20, 340 };
list.AddRange(a);

list.Remove(10); //10があればListから削除
//3,4,10,20,340

RemoveAllメソッド

Removeメソッドでは該当する値が複数あった場合、削除されるのは最初に見つかった値だけです。

なので、例えば10という値が複数Listに格納されている場合、全てのを削除するにはRemoveAllメソッドを使います。

List<int> list = new List<int>();

list.Add(3);
list.Add(10);
list.Add(4);

int[] a = { 10, 20, 10 };
list.AddRange(a);

list.RemoveAll(num => num == 10); //全ての10をListから削除

Debug.Log("Listの長さは" + list.Count); //長さは3
//3,4,20

RemoveAtメソッド

Listのインデックス番号を指定して削除ができます。

List<int> list = new List<int>();

list.Add(3);
list.Add(10);
list.Add(4);

int[] a = { 40, 20, 30 };

list.AddRange(a);
list.RemoveAt(2); // Listの2番目の要素を削除する 
//3,10,40,20,30

おわり

Listを使うことで値を自由に出し入れすることができました。
ということで、Listの基本的な使い方でした。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2