2015年11月1日日曜日

MonoBehaviourを継承している場合はAddComponentで

寒くなって参りました。風邪などには注意して毎日を過ごしていきましょう。

というわけで本題に。シーンを実行するとこの警告文が毎回出てきて鬱陶しいと感じていた。
以下がそのエラー文。

「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()
LevelControl:.ctor()
MapCreator:Start() (at Assets/Scripts/Game/MapCreator.cs:40)」

何を言われているかと言うと、
MonoBehaviourを継承しているところではnewではなくAddComponentしてねということでした。

private MapCreator MC = null;

MC = new MapCreator(); ← これはダメ
MC = gameObject.AddComponent<MapCreator>(); ← こっちが正解

0 件のコメント:

コメントを投稿