GetComponent()以外で他のクラスを参照するには?
やりたいこと
他のクラスを参照するとき、ゲームオブジェクトにクラスをアタッチして、GameObject.Find("object_name").GetComponent<MyClass>()
といった感じでアクセスする方法多いんだけど、アタッチしなくても参照できないかなぁ?と思いまして、その方法をメモ。
MonoBehaviourを継承しない場合
参照したいクラスがMonoBehaviourを継承しない場合は、コンストラクタでインスタンスを生成すればOK。
参照したいクラス using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gold { int gold; void Awake () { gold = PlayerPrefs.GetInt ("gold", 0); } public int GetMoney () { return gold; } }
参照の仕方 Gold gold = new Gold (); int now_gold = gold.GetGold();
MonoBehaviourを継承する場合
仮に、上のGoldクラスがMonoBehaviourを継承していたなら、実行するとこんな警告がでる。
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor()
MonoBehaviourを継承しているならGetComponent()を使いなさい、ということらしい。
ということで、下記の記事のようにスクリプトで作成したゲームオブジェクトにアタッチするか、ヒエラルキーにあるゲームオブジェクトにアタッチするか、どちらかをしないといけない。
以上。