The full warning message:
You are trying to create a
MonoBehaviour
using thenew
keyword. This is not allowed.MonoBehaviours
can only be added usingAddComponent()
. Alternatively, your script can inherit fromScriptableObject
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