0

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!");
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
moshe ralf
  • 489
  • 3
  • 12
  • 21
  • 10
    You absolutely are using the `new` keyword: `DetectPlayer dp = new DetectPlayer();` – Serlite Nov 16 '16 at 19:24
  • 2
    Unity doesn't like it when you try to create `MonoBehavior` derived objects using `new`. It expects you to use `Instantiate` instead for its internal housekeeping to work right. – Cody Nov 16 '16 at 19:43

1 Answers1

20

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>();
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
rygo6
  • 1,929
  • 22
  • 30
  • `What you want to do is` .. **if and only if** you wanted to create a new instance yes. Otherwise what you want to do would actually be to reference the already existing instance of that component .. e.g. either via the Inspector (by exposing a serialized field) or via `FindObjectOfType` etc – derHugo Feb 19 '23 at 19:19