- Home /
GetComponent returns null when using a generics class for T
So I'm making a game where I have a Player.cs script that instantiates the player ship, the player ship prefab has a StandardShip component attached to it. The StandardShip component inherits from PlayerShip which inherits from ship and so on until eventually it inherits from MonoBehaviour.
StandardShip.cs
public class StandardShip : PlayerShip<LaserBullet> {...}
PlayerShip.cs
public abstract class PlayerShip<T> : Ship where T : Bullet {...}
LaserBullet obviously inherits from Bullet, which in turn inherits from Monobehaviour too. Bullet.cs
public abstract class Bullet : MonoBehaviour, IPoolableEntity {...}
The error occurs inside the Player.cs file, GetComponent returns null even thought all the components inherit from MonoBehaviour so I don't know what I'm doing wrong.
Player.cs
string pathToPrefab = $"Prefabs/{PlayerPrefs.GetString(PlayerPrefsConstants.SELECTED_SHIP, null) ?? "StandardShip"}";
GameObject objectToInstantiate = Resources.Load<GameObject>(pathToPrefab);
PlayerShip<Bullet> ship = objectToInstantiate.GetComponent<PlayerShip<Bullet>>();
//var s = objectToInstantiate.GetComponent<Rigidbody2D>();
The Resources.Load returns the correct prefab and I tried getting the RigidBody2D, it worked. So I don't know what the problem is. I would really appreciate if someone could tell me what I'm doing wrong 'cause I can't figure this out.
Answer by sacredgeometry · Dec 06, 2020 at 06:41 PM
Probably for the same reasons:
// These work
var a = GetComponent<StandardShip>();
var b = GetComponent<PlayerShip<LaserBullet>>() as StandardShip;
// These do not
var c = GetComponent<PlayerShip<Bullet>>() as StandardShip;
var d = (StandardShip)GetComponent<PlayerShip<Bullet>>();
i.e. When using GetComponent StandardShip
is not a PlayerShip<Bullet>
it's a PlayerShip<LaserBullet>
because it doesn't support variance in that direction.
Reading
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/ https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance
Thank you for the answer, I didn't know this covariance and contravariance. I didn't know Generic with a derived class can't be casted to the same generic but with a base class so I'll have to search for another way of doing this.
Your answer
Follow this Question
Related Questions
NullReferenceException. GetComponent dose not work properly 2 Answers
Why is this null? Finding a script on an object 3 Answers
Object reference not set to an instance of an object in c#. 0 Answers
Assign collider and linerenderer to list 1 Answer
NullReferenceException - Editor script using GetComponent after AddComponent 1 Answer