GetComponents() returns null while GetComponent() returns non-null. WHY
Hello,
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.
Answer by andrew-lukasik · Dec 10, 2021 at 01:51 PM
>> 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...");
else
Debug.Log("I told you so");
Long story short: don't cast arrays in c#
Your answer
![](https://koobas.hobune.stream/wayback/20220613050417im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Value doesn't change in game when updated. 2 Answers
Highscore not working 0 Answers
Instanciated objects can only be seen if they were instanciated while looking to the left. 0 Answers
Unable to save the captured photo in hololens app. 0 Answers
Error!!! NullReferenceException: Object reference not set to an instance of an object 2 Answers