Why in unity i’m getting the warning: You are trying to create a MonoBehaviour using the ‘new’ keyword? [closed]

It is best to not think of MonoBehaviours as C# objects in the traditional sense. They should be considered their own unique thing. They are technically the ‘Component’ part of the Entity Component System architecture which Unity is based upon.

As such, a MonoBehaviour being a Component, it cannot exist without being on a GameObject. Thus creating a MonoBehaviour with just the ‘new’ keyword doesn’t work. To create a MonoBehaviour you must use AddComponent on a GameObject.

Further than that you cannot create a new GameObject at class scope. It must be done in a method once the game is running, an ideal place to do this would be in Awake.

What you want to do is

DetectPlayer dp;

private void Awake()
{
    GameObject gameObject = new GameObject("DetectPlayer");
    dp = gameObject.AddComponent<DetectPlayer>();
}

Leave a Comment