GetComponents() returns null while GetComponent() returns non-null. WHY


I am new to Unity and trying to get all Collider2D object in a script by gameObject.GetComponents(typeof(Collider2D)) but it returns null.
I replaced GetComponents() with GetComponent() and it returns a Collider2D object.

To make a problem clear, I wrote the below script and it stops at later assertion statement.

Collider2D[] colliders = this.gameObject.GetComponents(typeof(Collider2D)) as Collider2D[]; Collider2D collider = this.gameObject.GetComponent(typeof(Collider2D)) as Collider2D; Assert.IsTrue(collider != null); Assert.IsTrue(colliders != null);

What causes this?

Here is my environment:

  • Unity Version - 2020.3.24f1 Personal
  • OS Version - Windows 10 20H2 (OS BUILD 19042.1348)

Thank you.

gameObject.GetComponents returns null

This is not true. gameObject.GetComponents<Collider2D>() never returns null. Even where there are no components found. What has happened is you casted a Component[] to Collider2D[] and this is what returned you a null.

// don't  believe me?
var colliders = gameObject.GetComponents<Collider2D>();
if( colliders==null )
    Debug.Log("You were right! :T wat...");
    Debug.Log("I told you so");

Long story short: don’t cast arrays in c#