- Home /
What is the most efficient way to dynamically add a component, based on a string passed in.
At initialization, I want to dynamically create a large list of game objects. I will be attaching one component to each object from a set of possible scripts (all of which inherit from the same base class). An XML file will be read to tell me which script to attach for each object. What is the most efficient way to this?
Rather than having a long list of if-else-ifs
if(type == "type1")
{
gameObject.AddComponent<typeOne>();
}
else if(type == "type2")
{
gameObject.AddComponent<typeTwo>();
}
else if(type == "type3")
{
gameObject.AddComponent<typeThree>();
}
My initial thoughts are to use a look-up dictionary [string, System.type]. Is the optimal, or any other ways to approach this problem?
I'd go with the simplest -- the ifs you have now -- as these sorts of things tend to change a lot. For example, you may later decide to go with prefabs (with the scripts already on them.) Or may decide to list them ins$$anonymous$$d as X of each type.
Answer by siaran · May 07, 2015 at 09:42 PM
Your initial idea sounds perfectly fine to me. A dictionary seems a sensible way to approach this, so I would go with that.
+1
You can pass a string directly to AddComponent as long as the string is the name of a valid $$anonymous$$onoBehaviour class. Internally Unity probably just uses reflection to get the System.Type of that class. So a prepared dictionary would of course be faster, but not by much. How often do you add new components to your gameobjects? Even when you load in larger structures i doubt that the lookup of the class will be a bottleneck ^^.
However I just made a logic gate simulator and also create class instances by classname. I also created a Dictionary which i populate at start. In my case i don't use classes derived from $$anonymous$$onoBehaviour but derived from a certain interface. So i can't use AddComponent and have to use reflection.