How do I give an object a script component of a type specified by the calling source?
public static void Init<T>(GameObject target, bool preserveOriginal, string classTemplateToAssign)
{
MonoBehaviour[] mb = target.GetComponents<MonoBehaviour>().ToArray();
if (mb.Length != 0)
{
//PooledObject po = target.AddComponent<POTemplateScript>();
PooledObject po = target.AddComponent(T as System.Type);
//BlahBlah all below.
I don't understand how generics work, so that's definitely the first problem, but I think the T after the function name is the same kind of idea as GetComponent<> <-- this part. You're passing T as a parameter. I want the user to be able to pass a script class name, and it just adds a new script instance of that type.
Answer by AnOrdinarySandwich · Dec 24, 2020 at 09:02 AM
Generics are quite useful for sure. You're right about the GetComponent being a generic type, but its not a parameter, it indicates the type to be used. When trying to use a generic type to AddComponent, you're going to need the 'where' constraint, to make sure the given type is actually a MonoBehaviour (you won't need the classTemplateToAssign).
static public void Init<T>(GameObject target, bool preserveOriginal) where T : MonoBehaviour
{
...
PooledObject po = target.AddComponent<T>();
}
Your answer
Follow this Question
Related Questions
accessing a script using a variable with getComponent, then accessing a variable inside that script 1 Answer
Edit variable of component by type 0 Answers
How can you delete a MeshCollider?? CAN you delete a MeshCollider? 1 Answer
How to set a bool from a script equal to another bool from another script? 1 Answer
Activating Scripts in another Script? 2 Answers