Dynamic AddComponent?

Hey guys, I am looking for a way to add components that I either store in a list or anywhere to attach them to gameobjects,

foreach (string componentItem in listOfComponentsToAddToStartOfGame){
            GameObject gameObjectCheck = GameObject.Find(componentItem);
            if (gameObjectCheck == null){
                gameObjectCheck = new GameObject(componentItem);
               ******* gameObjectCheck.AddComponent<componentItem >();
               //This is where I wanted to attach components...

Thanks,

One of the AddComponent overloads takes a class name instead of a type. So just call it with the name of the class from your list.

Instead of storing the names of the classes, you can just store the list of components:

Include this line at the top of your script

using System.Collections.Generic;

Somewhere inside the class

List<Component> componentsToAdd; // Your list of components

void Start() {
    componentsToAdd = new List<Component>();
    componentsToAdd.add(/* some component */); // Repeat as necessary
}

When you want to add components

foreach (Component c in componentsToAdd) {
    someGameObject.AddComponent(c.GetType());
}

You can do it but it’s not pretty, you need to use the types and reflection like this:

    List<Type> componentList = new List<Type>();

    componentList.Add(typeof(Rigidbody));
    componentList.Add(typeof(Animator));

    GameObject go = new GameObject("MyGameObject");
    
    foreach(Type component in componentList)
    {
        var methodInfo = typeof(GameObject).GetMethods().Where(x => x.IsGenericMethod)
             .Where(x => x.Name == "AddComponent").Single();
        var addComponentRef = methodInfo.MakeGenericMethod(component);
        addComponentRef.Invoke(go, null);
    }