Easy? Convert System.Type to UnityEngine.Component

I have a function where I’m returning a System.Type, and need to convert it into a Component.

a) Is this possible, if so how

b) Is it possible to return a Component instead from a function rather than System.Type

I haven’t been able to do either.


public class aClass {
   public System.Type GetAScript() {
     return typeof(BeamProjectile);  //Where BeamProjectile is a sub class that implements a base class that inherits from MonoBehaviour

class SomeOtherClass {
    public aClass;
    public DoSomething() {
      System.Type st = aClass.GetAScript();
      GameObject go;
      go.AddComponent<st>(); /// <-- failure

Just use…


… in the last line in your example, as AddComponent is overloaded to accept either a string with the type name, a Type, or a parametric type.

For reference, check second overload here.

Try something like:

public T GetScript<T>()
    return T;

var st = GetScript<BeamProjectile>();
GameObject go;

But I don’t get why do you need to do that and not just:


I faced similar problem, and saw that it’s not possible to use System.Type variables in generics.
See for example here

You can use reflection to instantiate component, but you can have a problem on mobile devices.

For your case probably will be reasonable to use Strategy Pattern