LoginSignup
6
7

More than 5 years have passed since last update.

Unity の null 比較

Posted at

TL;DR

UnityEngine.Object.operator == は override されているので null との比較は気をつける。

Unity - スクリプトリファレンス: Object.operator ==

Test

Component の拡張メソッド TryGetComponent<T> の実装をテストする。
取得したい Component が存在しなければ、 false になる。

[Test]
public static void TryGetComponentWhenNotExistsReturnFalse()
{
    var gameObject = new GameObject();
    var rigidbody = gameObject.AddComponent<Rigidbody>();
    BoxCollider outBoxCollider;
    Assert.IsFalse(rigidbody.TryGetComponent(out outBoxCollider));
}

失敗する実装

public static bool TryGetComponent<T>(this Component component, out T t)
{
    t = component.GetComponent<T>();
    return t != null;
}

成功する実装

public static bool TryGetComponent<T>(this Component component, out T tComponent)
    where T : Component
{
    tComponent = component.GetComponent<T>();
    return tComponent != null;
}

generic 型制約 where T : Component をつける。

where (ジェネリック型制約) (C# リファレンス) | Microsoft Docs

理由

失敗する実装では TSystem.Object なので、 != nulltrue になる。
成功する実装では TComponent の継承に制約したため、 UnityEngine.Object となり、 null 比較が正しく行われる。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7