You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent().
A MonoBehaviour only works when it is attached to a GameObject, because Unity creates, updates and destroys it as part of that object. new gives you a C# object with no GameObject, so Unity warns and the object never gets Update, Start or a transform.
Read the Console line first
The stack trace names the line with new YourScript().
Common causes
Creating a component with new
To give an object a new component at runtime, call AddComponent on its GameObject.
Using a MonoBehaviour as a data holder
If the class only stores data and has no Update or transform, it does not need to be a MonoBehaviour. Make it a plain [System.Serializable] class or a ScriptableObject.
The fix
// A component, attached to an object
var health = enemy.AddComponent<Health>();
// A data holder, created with new
[System.Serializable]
public class ItemStack { public string id; public int count; }
var stack = new ItemStack { id = "gem", count = 3 };Stop it coming back
Decide early whether a class is a component (it lives on a GameObject) or data (it does not), and only derive from MonoBehaviour for the first.
Questions
- Why does the object I made with new seem to work at first?
- You get a C# object with no native side: it has no GameObject, its
transformis null, and Unity never calls its Awake, Start or Update. Anything that touches the engine fails later. Add it withgameObject.AddComponent<T>()instead. - I only need a class to hold data. What should I use?
- A plain C# class without
: MonoBehaviour. Mark it[System.Serializable]and it shows up in the Inspector as a field of the component that holds it, and JsonUtility can save it. - Is the same true for ScriptableObject?
- Yes. Create ScriptableObjects with
ScriptableObject.CreateInstance<T>(), or as assets through a[CreateAssetMenu]menu item. Unity warns if you usenew.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.