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.
That is as good as my hack right now, naming the prefab the same as the concrete Spell component
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.