C# – Why in unity i’m getting the warning: You are trying to create a MonoBehaviour using the ‘new’ keyword?

cunity3d

The full warning message:

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

And in both scripts I'm not using the new keyword:

The DetectPlayer script:

public class DetectPlayer : MonoBehaviour 
{
    private int counter = 0;

    private void OnGUI()
    {
        GUI.Box(new Rect(300, 300, 200, 20),
            "Times lift moved up and down " + counter);
    }
}

The Lift script:

public class Lift : MonoBehaviour 
{
    private bool pressedButton = false;
    private DetectPlayer dp = new DetectPlayer();

    private void OnGUI()
    {
        if (pressedButton)
            GUI.Box(new Rect(300, 300, 200, 20), "Press to use lift!");
    }
}

Best Answer

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>();
}