- Home /
 
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.
Example:
 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
     }
 }
 
              Doesn't this work?
 public BeamProjectile GetAScript() {
     return new BeamProjectile();
 }
 
                 Answer by Azrapse · Oct 22, 2013 at 09:56 AM
Just use...
 go.AddComponent(st);
 
               ... 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.
Update: I thumbed this up - this is what I ended up doing.
Answer by dorpeleg · Oct 22, 2013 at 08:25 AM
Try something like:
 public T GetScript<T>()
 {
     return T;
 }
 
 var st = GetScript<BeamProjectile>();
 GameObject go;
 go.AddComponent<st>();
 
               But I don't get why do you need to do that and not just:
 go.AddComponent<BeamProjectile>();
 
              I'm using an abstract class of 'projectiles' in a new weapon system, and I'm storing them all a generic object pool, where they could be of any base type projectile..
Answer by nicloay · Oct 22, 2013 at 08:30 AM
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
Your answer