Casting to a Type using a String

Hello, I simply want to fetch a component from a gameobject and cast it using the AS-operator to the proper type.
I do know the name of the type on runtime only and that name is stored in a string.

Using the type directly in code works fine:

go.GetComponent(configuration) as Config1; // works 

But as I pointed out, I don’t know about the type before runtime. All I have is a string and obviously this does not work:

go.GetComponent(configuration) as "Config1"; // can not work

I tried to use getType to convert the string to the correct type like so:

go.GetComponent(configuration) as Type.GetType("Config1"); // compile error

That results in the following error in Unity Editor: Unexpected symbol `(’ (but no Error in MonoDevelop)

So, how do I convert the String “Config1” to a valid casting information?

Greets

Use GetComponent < YourBaseType >(). Create a virtual method(s) in the base type that can do the config specific handling, override those methods in the child classes. Always use the virtual methods to do platform specific things depending on the config object instance.

Regardless, at some point in your code you’ll need specific code to handle the specific differences such as different config screens, different code paths.

Another option for that sort of thing is to use conditional compilation, which might be better for your needs.

You need to look up reflection. Convert.ChangeType() in specific.

The problem with using reflection in Unity is it isn’t supported by all platforms (to the best of my knowledge).

If it’s just a case of proper subtyping and you don’t have many types, you could cheat and use a switch statement (switch on the string and in each case do a normal cast).

Dave has a good point. What you are trying to do may not be necessary. Why do you think you need to cast? It might not be the best solution for the problem you are trying to solve.