AddComponent with dynamic parameter

Hi there,

it’s a long time that I used Unity so I stumbled upon the new AddComponent.
And I switched to C# - so problems have doubled :slight_smile:

My problem is, that I need to pass a string at runtime to AddComponent but I can’t get it to work.
I’ve got a lot of scripts like: “Level001.cs”, “Level002.cs” and so on.

This is working - but not what I want:
gameObject.AddComponent();
gameObject.GetComponent().Test();

This is not working
string levelname = “001”;
gameObject.AddComponent<“Level” + levelname>();
gameObject.GetComponent<“Level” + levelname>().Test();

Is it possible at all?
Can you tell me how?

Examples are appreciated :wink:

Greetings,
Whitedrow

What about that way:

// Adds the script named FoobarScript to the game object
gameObject.AddComponent ("FoobarScript");
// Gets the script named FoobarScript from the game object
gameObject.GetComponent ("FoobarScript");
This is not working
string levelname = "001";
gameObject.AddComponent<"Level" + levelname>();
gameObject.GetComponent<"Level" + levelname>().Test();

The problem here is that you using the generic type of Add and GetComponent. As This documented you only alow use Type inside . I think you should take a look here for more information about generic type. An other way to approach your Idea is use Type in C#

Something like this: (not tested yet)

string levelname = "001";
var t = Type.GetType("Level" + levelname).
gameObject.AddComponent(t);
gameObject.GetComponent(t).Test();

P/S: But I highly recommend you use

gameObject.AddComponent< typeof(t) >();
gameObject.GetComponent< typeof(t) >().Test();

instead

Hope this help.

Hey there,

From what I can tell, your issue is that you are trying to use a string to add a component. Sadly, AddComponent() was removed from unity 5.0 and onward, in an attempt to break dependencies.

Here is a post explaining the work arounds you can attempt:

I hope this helps!