-1

I'm using Unity 5.6

I need use something like AddComponent(variable).

For example:

I have empty scene.

I have List<string> called cpList that contains the names of components.

Now I need something like this:

oj = new GameObject;
forEach(var cp in cpList ) {
    oj.addComponent(cp);
}

But I can't do that, because AddComponent(string) is deprecated.

noob
  • 21
  • 2

3 Answers3

0

Try this?

oj.addComponent(Type.GetType(cp));

Maybe you just need to get the Type of the component

Andreito
  • 1
  • 6
0

I would very much like to know what is your usecase here?

You can something like Type.GetType using the full reference name like e.g. "UnityEngine.Rigidbody" but I'm not sure if this is what you would really want to do

var obj =  new GameObject();
foreach (var cp in cpList)
{
    // Maybe try full names like e.g. "UnityEngine.Rigidbody"
    obj.AddComponent(Type.GetType(cp));
}

this is very error prone and not very efficient.

Alternatively also using Reflection and Assembly.GetType but then you need to know at least one type in the same assembly:

Assembly asm = typeof(UnityEngine.Object).Assembly;
Type type = asm.GetType("UnityEngine.Rigidbody");

You could rather use some hardcoded dictionary like e.g.

public static readonly Dictionary<string, Type> componentTypes = new Dictionary<string, Type>()
{
    // some examples
    {"Camera", typeof(Camera)},
    {"SomeOtherScript", typeof(SomeOtherScript)}
}

and then do something like

var obj =  new GameObject();
foreach (var cp in cpList)
{
    if(!componentTypes.ContainsKey(cp))
    {
        Debug.LogError($"For the name {cp} no type was defined!");
    }
    obj.AddComponent(componentTypes[cp]);
}

Same could be done also with a simple switch - case.

Trade-off ofcourse you need one line/entry for each component you are going to tackle.


Note: Typed on Smartphone so no warranty but I hope the idea gets clear.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • First method don't work. I'm testing it in debug mode and: var = Assembly.GetExecutingAssembly().GetType("Rigidbody"); return Null. Second method suggests\conduct me to know\enumerate all Unity3d components before using so it isn't good for me. – noob Nov 19 '19 at 13:07
  • Maybe try the full name `UnityEngine.Rigidbody` . Also in this case you should rather use `Type.GetType` since the first example assumed you are talking about custom components which probably are built into another assembly as Unity built-in ones. – derHugo Nov 19 '19 at 16:06
0

You could go for this approach if you are looking for a quick fix:

foreach (var cp in cpList)
{
    if(cp.Equals("Text"))
        ob.AddComponent(Text);
    else if(cp.Equals("Rigidbody"))
        ob.AddComponent(Rigidbody);
    //Add more here
}

Compared to the other examples, this requires a lot more work, and is somewhat prone to type errors.

Edit: You may also have to handle the cases where you can't add two ui components.

reecemcg
  • 28
  • 4