Search Unity

Warning message "public class OBJ : MonoBehaviour"

Discussion in 'Scripting' started by giancamati, Nov 10, 2010.

  1. giancamati

    giancamati

    Joined:
    Aug 4, 2010
    Posts:
    518
    Hello Guys, I have a class called OBJ writte in C# and I derived it from a MonoBehaviour". In another a javascript I call

    var obj = new OBJ();

    which causes the following warning:

    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
    UnityEngine.MonoBehaviour:.ctor()
    OBJ:.ctor(String, Boolean)
    createObjects:Start() (at Assets/createObjects.js:20)

    can you tell me what's the problem?
    Thanks
    Giancarlo
     
  2. Chris-Sinclair

    Chris-Sinclair

    Joined:
    Jun 14, 2010
    Posts:
    1,326
    If it extends MonoBehaviour, then you have to use the AddComponent method to instantiate the script and attach it to an existing GameObject.
     
  3. Ntero

    Ntero

    Joined:
    Apr 29, 2010
    Posts:
    1,436
    If you want an object unattached to any GameObjects or not existing in the world don't use MonoBehaviour. look at ScriptableObject or just don't inherit. Components and all child parts are designed to be attached to GameObjects. If you use new, it'll never initialize your class, nor will it call Awake, Start, Update, FixedUpdate, and all other Monobehaviour functions, removing the need for a MonoBehaviour.
     
  4. giancamati

    giancamati

    Joined:
    Aug 4, 2010
    Posts:
    518
    Uhm I guess I'm gonna adopt Ntero suggestion but FizixMan, really thank you as yo made my mind clear. The purpose of my OBJ script is just to create a GameObject with a new Muesh ont the fly so I guess I'll get rid of the inheritance

    super thank you!