-
Notifications
You must be signed in to change notification settings - Fork 134
MonoBehaviors must be instantiated with GameObject.AddComponent instead of new
If the new
keyword is used to create a MonoBehaviour
, the call will fail at run time. This is because a MonoBehaviour
is a component, and needs to be attached to a GameObject
. Without being attached, the special methods such as Start
and Update
, etc. won't get called.
This inspection will highlight any attempts to new
a MonoBehaviour
derived class, and provides an Alt+Enter quick fix to rewrite the new
as a call to GameObject.AddComponent<T>()
, allowing you to choose which GameObject
to add the new component to.
This inspection corresponds to the Unity runtime warning "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."