Cannot create MonoBehaviour with "new' keyword?

I’m making an RPG where the player creates a party of different Character types. I’m trying to make it so four new Character classes are created and stored in an array in a PartyManager with there values be set by starting from prefab Characters, but the array is being filled out. I get a warning in the console about not being able to create a new Monobehaviour with the “new” keyword but i don’t understand that one.

Line 4 is where the new Character should be made and set.

public void SetCharacterType()
    {
        partyManager.characterClass[partyIndex] = characterSpritesIndex;
        partyManager.characters[partyIndex] = new Character(partyManager.characterClasses[characterSpritesIndex].GetComponent<Character>());
    }
 public Character(Character characterPreset)
    {
        job = characterPreset.job;
        spriteIndex = characterPreset.spriteIndex;

        partyIndex = characterPreset.partyIndex;

MonoBehaviours are Components. This means they are inextricably attached to GameObjects at all times. If you create a MonoBehaviour with new, then obviously it is not attached to a GameObject. It cannot exist in this state, so Unity gives you a warning that this is bad. You should heed this warning. MonoBehaviours are meant to only exist when they are attached to GameObjects. You can create one by Instantiating an existing one (such as from a prefab), or by using the AddComponent method on GameObject.

If you have a class that you don’t intend to attach to a GameObject as a component, there is no need to make it derive from MonoBehaviour.

1 Like

The MonoBehaviour class is a bit special, it has deep hooks into the way Unity works. To add a component based off MonoBehaviour to an existing object, do this:

CharacterBehaviour createdCharacterBehaviour = myGuy.gameObject.AddComponent<CharacterBehaviour>();