LoginSignup
4
5

More than 3 years have passed since last update.

MonoBehaviourが本当にnullか否かを確認するにはReferenceEqualsとis演算子を使え

Last updated at Posted at 2020-10-04

PR: CADDiではバックエンドエンジニア、フロントエンジニア、アルゴリズムエンジニア、SRE等などを募集しています

MonoBehaviournull の比較が特殊であることは周知の事実である。これは MonoBehaviour の基底クラスである UnityEngine.Object のメソッド Object.operator boolObject.operator ==、そして Object.operator != に起因する。

operator boolnull との比較は同じ結果が得られるため、null との比較においては operator ==operator != を使う意味はほぼ無い。

たとえば、状態を常に正しい状態に保つためにプロパティの set で単なる代入以外の処理を行っている場合、オブジェクトが本当に null かどうかを確認してから代入したい場合がある。

SomeType someField;
SomeType SomeProperty {
    get => someField;
    set {
        someField = value;
        SomeMethod();
    }
}

この様な場合、System.Object.ReferenceEquals を用いることでオブジェクトが本当に null か否かを確認することができる。

void UpdateSomeProperty() {
    if (!System.Object.ReferenceEquals(null, SomeProperty) && !SomeProperty) {
        SomeProperty = null;
    }
}

System.Object.ReferenceEqualsis nullis object で置き換えることで、更に簡便に記述することができる。

void UpdateSomeProperty() {
    if (SomeProperty is object && !SomeProperty) {
        SomeProperty = null;
    }
}

null であることを確認する場合は is null を、null でないことを確認する場合は is object を用いる。

null 以外との比較には変わらず ReferenceEquals が使える。

SomeType someField;
SomeType SomeProperty {
    get => someField;
    set {
        if (ReferenceEquals(lockTarget, value)) {
            return;
        }
        someField = value;
        SomeMethod();
    }
}

void UpdateSomeProperty() {
    if (!SomeProperty) {
        SomeProperty = null;
    }
}
4
5
1

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
4
5