So, Unity has informed me that AddComponent(string) is deprecated/obsolete, therefore I cannot use it. My goal of this question is to find out how to add my own custom script to an object by name, passed in a method. I want to do exactly this:
public void AttachComponent(string component, GameObject obj) {
obj.AddComponent(component);
}
but this is now obsolete. How can I pass a type as an argument so that component is not treated like a variable, but rather a type, and I can pass it to AddComponent? Thanks in advance.
You can convert a string to a type with Type.GetType.
So like this.
public void AttachComponent(string component, GameObject obj) {
obj.AddComponent(Type.GetType(component));
}
Which is probably exactly what the string version did under the hood.
Its worth noting that adding a component by string should be relatively rare. It only makes sense in a few situations where you can’t know the type of component to be added until runtime.
Plan was to add multiple event scripts and only add them when needed, instead of crowding one script or crowding a GameObject in the inspector with scripts/methods. Will this cause a problem?