I am currently using c#. I am trying to find a component that is not specified at runtime. I want to find the component by its name using a string. Then I want to add it to a GameObject.
Object.AddComponent((Type)System.Activator.CreateInstance(Type.GetType(Grid[0].Colors[0].Components[0]));
Grid[0].Colors[0].Components[0] is the array of strings, currently just testing with the first element in the array.
When I use “UnityEngine.Rigidbody”, it errors with:
TypeLoadException: Could not load type
‘UnityEngine.Rigidbody’.
What am I doing wrong?
Bunny83
2
Your use of the Activator is completely wrong here. The Activator creates an instance or a C# class. You can not create components using the constructor. AddComponent requires a System.Type as parameter. GetType does return the System.Type object. So just do
var type = Type.GetType(Grid[0].Colors[0].Components[0]);
if (type != null)
Object.AddComponent(type);
else
Debug.LogWarning("Type " + Grid[0].Colors[0].Components[0] + " not found");