- Home /
Components using Generics
I have a class using generics:
ProjectileWeapon.cs:
public class ProjectileWeapon<T> : WeaponBase where T : ProjectileEffect
When I try to drag the script in the Editor I get an error saying the class name doesn't match the file name.
When I try to use AddComponent I don't get any error but it returns 'null':
ProjectileWeapon<PlasmaProjectile> weapon = gameObject.AddComponent<ProjectileWeapon<PlasmaProjectile>>();
print("weapon = " + weapon.name);
Weapon is 'null' and I get an Object reference exception in the print statement. Am I doing something wrong or is Components using generics just not supported?
I found this page, is this the same problem? http://answers.unity3d.com/questions/18061/can-generics-appear-in-the-editor
Answer by Skjalg · Dec 04, 2010 at 10:15 AM
Yes that is the same problem. What you are trying to do is not possible. What you should instead do is make new Monobehaviour scripts for each class that inherits from ProjectileEffect, like PlasmaProjectile.
public class PlasmaProjectileWeapon : ProjectileWeapon<PlasmaProjectile> {
}
Unity3D could have done something about this, but I dont think it is a priority.
Your answer
![](https://koobas.hobune.stream/wayback/20220613085633im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
differences: generic GetComponent. 3 Answers
2D Animation does not start 1 Answer
What is the syntax for adding some generic type of component without an object reference? 1 Answer
How to create a List containing all the different variables within a script (regardless of type)? 1 Answer
Why is this generic "Get component if null" code not working 5 Answers