Forcing a type conversion from an abstract class C#

I have a class of objects in an object pool that are all derived from an abstract class, but this is failing:

//SUProjectile : Base abstract class
//BeamProjectile : derived from SUProjectile

SUProjectile SU_P; 
GameObject goProjectile = TheObjectPool.GetNextObject("Heretic Juice");
System.Type st = GetProjectileType("Heretic Juice");
SU_P = (st) goProjectile.GetComponent(typeof(st)); //<-- fail, can't use "st" in this way apparently.. 

This is, of course just part of the problem.

I have an objectpool, it stores many types of projectiles all derived from the base abstract class of SUProjectile. There may be hundreds of projectile types eventually, so I’d like to do this at runtime…

I think it would be easier to simply use the generic version of GetComponent with the base type:

SU_P = goProjectile.GetComponent< SUProjectile > ();

You do not need the GameObject in the middle.

Simply:

SUProjectile SU_P; 
SU_P = TheObjectPool.GetNextObject("Heretic Juice");

if all objects inherits from SUProjectile, they are all of this type so they can directly be stored into an object of type SUProjectile.

Then if you are trying to access a method from the SUProjectile you can call it, if you need to access something from a sub class you can try:

if(SU_P is SubClass){
    SubClass sub = (SubClass)SU_P;
    sub.SubMethod();
}

In line 6 you get the Type in st. An object of type Type is an object with information about a type in C#.

In line 7 you do weird stuff.

First you call the method GetComponent passing as parameter not st, but typeof(st).
What typeof() does is returning a Type object with information about the type of the parameter. In this case the parameter of typeof(st) is st, that is of type Type. So the typeof() call is returning a Type object with information about class Type (Yes, you have made there a superconfusing tonguetwister in C#. :smiley: )

Then you try to cast the returning value into (st), but st isn’t a type, but an object of type Type, that is, an object with information about a type. So the compiler doesn’t let you. You cannot cast to an object, only to a type.

What the last line should look like is

SU_P = (SUProjectile) goProjectile.GetComponent(st);