LoginSignup
2
0

More than 3 years have passed since last update.

Unityのプレハブとnewについて

Last updated at Posted at 2021-02-05

Unityのプレハブを使っていて、引っかかる点があったので共有します。

プレハブにアタッチされているコンポーネントです。

PrefabAttach.cs
using UnityEngine;

public class PrefabAttach : MonoBehaviour
{
    SampleClass _sample = null;

    //SampleClassをnewするメソッド
    //自分のクラスを返却
    public PrefabAttach InstantiateClass()
    {
        _sample = new SampleClass();
        return this;
    }

    //SampleClassの中の、_countをログに表示するメソッド
    public void View()
    {
        Debug.Log(_sample._count);
    }
}

public class SampleClass
{
    public int _count;
}

シーンに追加されているオブジェクトにアタッチされているコンポーネントです。

PrefabAttach.cs
using UnityEngine;

public class PrefabLoader : MonoBehaviour
{
    void Update()
    {
        //Aキーが押されたとき
        if (Input.GetKeyDown(KeyCode.A))
        {
            //プレハブをリソースフォルダからロードし、SampleClassをnewしてから変数に入れる
            PrefabAttach attach = (Resources.Load("Prefab") as GameObject).GetComponent<PrefabAttach>().InstantiateClass();
            //SampleClassの_countをログに表示
            attach.View();

            //プレハブをリソースフォルダからロードし、Instantiateしてシーンに追加する
            GameObject game = Instantiate(Resources.Load("Prefab") as GameObject);

            //Instantiate前にプレハブの中のクラス、SampleClassをnewしたので、
            //きっとログに表示されるはず...
            game.GetComponent<PrefabAttach>().View();
        }
    }
}
実行結果
NullReferenceException: Object reference not set to an instance of an object
PrefabAttach.View () 

はいエラーです。

・プレハブをロードした後、シーンに追加する前にGetComponentできる
・シーンに追加する前にGetComponentしたコンポーネントへの参照と
追加した後のコンポーネントへの参照は別物
・変数なら、プレハブに加えた変更を保持している
・プレハブのままクラスをnewしても意味がないよ

とりあえず今回わかったのはこんな感じです。
以上です。

2
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
2
0