- Home /
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?
Answer by whydoidoit · Oct 29, 2012 at 06:06 PM
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;
}
This is a decent solution to the issue. Doesn't quite work in my case, as my factory object is actually a clone factory, so I have the item/monsters instances created beforehand like so: Factory.Register($$anonymous$$onster.Ogre, new $$anonymous$$onster("Ogre", 2, 13, 42, Location.All)); Factory.Register($$anonymous$$onster.Giant, new $$anonymous$$onster("Giant", 4, 26, 84, Location.All));
When the Factory.Create method is called it actually clones the existing instance, rather than simply creating one from scratch. However, turns out I can't create class instances using the 'new' keyword when they derive from $$anonymous$$onoBehaviour, so I need to change how I'm storing this information.
Still, I believe your solution and the one below solves my original issue.
Yes you can only create $$anonymous$$onoBehaviours by using AddComponent<T>() which basically instantiates it and calls Awake() instantly.
Answer by kmeboe · Oct 29, 2012 at 06:10 PM
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?