GetComponentsではNullReferenceExceptionエラーが出ない

はじめに結論

GetComponentで取得したオブジェクトを呼び出す時に
nullの場合NullReferenceExceptionエラーが
出るのに対して

GetsComponentsで取得したオブジェクトを呼び出す時に nullの場合エラーが何もでないという話です。

実際にどうなるか

スクリプトの準備

今回はGetComponentTest,GetComponentsTest,TestClassの3つを使います。

まずGetComponentTest.cs

gist.github.com

次にGetComponentsTest.cs

gist.github.com

最後にTest.cs

gist.github.com

Unityで結果を見てみる。

それではUnityでどうなるか見てみましょう。 GetComponentTest.csだけアタッチした場合

f:id:hiromunomymail:20210617175323p:plain

f:id:hiromunomymail:20210617175136p:plain

GetComponentsTest.csだけアタッチした場合

f:id:hiromunomymail:20210617175226p:plain

終わりに

GetComponentsで取得したオブジェクトを呼び出す時nullだとしてもエラーが発生しないお話でした。
厳密にはnullではないのかと思いますが
どちらにせよ今後は使い方に気を付ける必要があると思います。