コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】GetComponent と TryGetComponent の違い

GetComponent の場合

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        var result = GetComponent<Rigidbody>();
        if ( result != null )
        {
        }
    }
}

アタッチされていないコンポーネントを GetComponent すると

f:id:baba_s:20191023170910p:plain

Unity エディタ上でのみ GC Alloc が発生します
(ビルドしたアプリケーションでは GC Alloc は発生しません)

TryGetComponent の場合

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Update()
    {
        if ( TryGetComponent<Rigidbody>( out var result ) )
        {
        }
    }
}

アタッチされていないコンポーネントを TryGetComponent しても

f:id:baba_s:20191023171155p:plain

GC Alloc は発生しません

参考サイト様