How to add an existing script instance to a GameObject

My game will have hundreds of items/monsters and since I do not want to create a derived class for each of these items/monsters I use a single Monster and Item class, with fields for name, strength, damage, etc, that will differ for each type of item/monster. I have a factory class that will create the Monster/Item instance and automatically pass the field values via the constructor. In then end I can create a new item/monster by passing a monster type enum, like so:

Monster goblin = Factory<Monster>.Create(Monster.Goblin);

The problem is when I create a new monster class instance I don’t know how to attach this particular monster instance as a Component to the new GameObject. I really want to do something like this, which obviously does not work:

Monster goblin = Factory<Monster>.Create(Monster.Goblin);
GameObject game_obj = new GameObject(goblin.Name);
game_obj.AddComponent(goblin);

Does anyone know how to add a particular script instance to a GameObject, or perhaps know of another way to do what I am trying to do?

Presumably your Monster class inherits from MonoBehaviour so it can be a component? Presuming it does then all you need to do is modify your factory method to take the game object you want to add the instance to.

T Create(GameObject gameObject, SomeThing value)
 {
      var component = gameObject.AddComponent<T>();
      //Some other initialization
      return component;
}

Hey there,

If it were me, I would have the factory create the game object itself. That way, the factory can call AddComponent to create the script on the game object, and then populate the script’s members before returning the completed GameObject. You may not be able to do this via constructor (since AddComponent will call the default constructor for you), but can use accessor methods instead.

Does this approach work for you?