概要
クラス型の配列を使おうとしてつまづいた時の事を共有したいと思います。
本文
TestClassの配列を用意して初期値を設定するため0番目の要素に値を入れようとしたら
class TestClass
{
public string name;
public int age;
public TestClass(string name, int age)
{
this.name = name;
this.age = age;
}
}
private TestClass[] testClass = new TestClass[5];
void Start()
{
testClass[0].name = "鈴木";
testClass[0].age = 37;
}
以下のようなエラーが表示されました。
NullReferenceException: Object reference not set to an instance of an object
この場合は以下のように書けばエラーは表示されなくなります。
class TestClass
{
public string name;
public int age;
public TestClass(string name, int age)
{
this.name = name;
this.age = age;
}
}
private TestClass[] testClass = new TestClass[5];
void Start()
{
testClass[0] = new TestClass("鈴木", 37);
testClass[1] = new TestClass("榊原", 14);
testClass[2] = new TestClass("森田", 51);
testClass[3] = new TestClass("山田", 19);
testClass[4] = new TestClass("藤井", 23);
}
最初のnewで配列を宣言して
private TestClass[] testClass = new TestClass[5];
次のnewでクラスのインスタンスを生成する。2段階の手順が必要だったんですね。(最初のコードでエラーが出たのはインスタンスが作られてないのにそれにアクセスしようとしているから)
testClass[0] = new TestClass("鈴木", 37);