Get concrete class name from a prefab component

Hey guys

I have an abstract class Spell and derived classes, e.g. SimpleFireballSpell and WaterjetSpell. Moreover, there are prefabs that are made out of empty objects and that particular spell component attached.
Now, what I was trying to do is to get the name of the derived class, e.g. WaterjetSpell but ended up getting the name of the prefab.

I tried

Spell s = ...
s.name;
s.GetType().ToString();

but both returned me the name of the prefab (e.g. WaterjetPrefab).

How can I get the name of the concrete class of a component that is attached to a prefab if not by using GetType()?

s.GetType().FullName should give you the class name of the component you’re dealing with.

Unless the class name is WaterjetPrefab, your likely printing something else?

in a rare case where someone would override (via the new keyword) GetType() to return anything other than a System.Type, you could try ((System.Object)s).GetType().FullName

Thx, will try it out later.
But it looks like it will print me the fully qualified name. Is there a function to return the type name without qualification (is that the right word? lol), i.e. “WaterjetSpell”?

ok so,
.AssemblyQualifiedName will get you the namespace followed by the type name then the assembly and public key ect. Probably not what you want.
.FullName (Not AssemblyQualified name) will get you the namespace and type name. Unless “WaterjetSpell” is inside a namespace this is likely the best approach to use.
.Name excludes any namespace proir. So if WaterjetSpell is in a namespace or not “WaterjetSpell” will be returned. The reason this is likely not most ideal is if you have any name conflicts with other namespaces. This will give you exactly what you want, but depending on name collisions between other namespaces may not be the best choice.

I would say, since unity defaults the ‘new behaviour’ script to not use any namespace, most scripts are going to be in the global namespace where .FullName is going to equal .Name for any of your own types.

Out of curiosity, what’s the rest of this line?

As a hack you could simply make a public field called name :slight_smile:

Spell s = myPrefabGO.GetComponent();

That is as good as my hack right now, naming the prefab the same as the concrete Spell component :wink:

But as with my code (shouldnt include anything special), name returns me the name of the prefab. Didn’t check out fullname unfortunately; didnt have time.

Type does not have a ‘name’ property. it should be .Name (big N). Whatever your dealing with is not a Type, where ever your getting “WaterjetPrefab” your dealing with the actual prefab.

1 Like