# Adding components to a GameObject referenced within code

So in my project, I have a class called ComponentRegistry. The idea of this class is to store a dictionary of components and their names. For example:

    public Dictionary<string, MonoBehaviour> registry;
public MonoBehaviour testComponent;

void Start(){
registry = new Dictionary<string, MonoBehaviour> ();
}

public MonoBehaviour GetScript(string name)
{
return registry[name];
}


Then in a separate class, I will access this dictionary using a string in order to retrieve the associated component, subsequently adding the associated component to the gameObject.

    foreach (string comp in blockInfo.components) {

//For each of the components that need to be added

//I know this is incorrect, but the idea is there
}


Just for understanding, compReg is an instance of the ComponentRegister class stored as a static variable within my ScriptMaster class.

But no matter what I try, I have not been able to get this to work. I have switched endlessly between different formatting of adding components to gameObjects, alternating between using Components and MonoBehaviours, adding by type.

Thank you for any insight.

• "I have not been able to get this to work" - how would you like it to work? What exactly didnt work while using described approaches? And most importantly, what are you trying to solve with this? – wondra Feb 28 '17 at 18:55
• The end goal is to be able to add components to a gameObject that are stored in a dictionary in a script. No fomat of AddComponent I can make to work with what I have in place, the format essentially being "AddComponent(ComponentFromScript)" I believe that I am not passing/using the right variable type for storing a constructor. The proposed solution is that I can dynamically add scripts based on the type of object it is. – Harry Wilkins Feb 28 '17 at 19:15
• Do you want to add specific script (= instance) or script of specific type or perhaps copy of specific instance? There are huge differences between those and you do not specify what exactly you are after. – wondra Feb 28 '17 at 19:20
• Yes, so I want an equivalent of this: AddComponent<RigidBody>(), but instead of RigidBody, I pass a type stored in a dictionary, so I would assume I would be looking for an instance of that type. – Harry Wilkins Feb 28 '17 at 19:31

You probably wanted to create new instance of said script instead of passing reference to an existing instance. In order to do that, you can either implement the Factory pattern, or one of the IConeable variations/semantics - which would also allow you to have several "default" settings of one script.
//you should be able to get the correct name by typeof(T).FullName