3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Unity初級]クラスの配列について

Last updated at Posted at 2023-06-23

概要

クラス型の配列を使おうとしてつまづいた時の事を共有したいと思います。

本文

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);
3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?