0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】gameObject や transform に頻繁にアクセスする場合はキャッシュしたほうがいい

Last updated at Posted at 2024-08-04

検証したバージョン

Unity 2022.3.12f1

検証コード

GameObject
using UnityEngine;

public class GameObjectTest : MonoBehaviour
{
    private GameObject _gameObject;

    private void Start()
    {
        _gameObject = this.gameObject;
    }

    private void Update()
    {
        Test1();
        Test2();
    }

    private void Test1()
    {
        for (int i = 0; i < 10000; i++)
        {
            var obj = this.gameObject;
        }
    }

    private void Test2()
    {
        for (int i = 0; i < 10000; i++)
        {
            var obj = _gameObject;
        }
    }
}

Transform
using UnityEngine;

public class TransformTest : MonoBehaviour
{
    private Transform _transform;

    private void Start()
    {
        _transform = this.transform;
    }

    private void Update()
    {
        Test1();
        Test2();
    }

    private void Test1()
    {
        for (int i = 0; i < 10000; i++)
        {
            var transform = this.transform;
        }
    }

    private void Test2()
    {
        for (int i = 0; i < 10000; i++)
        {
            var transform = _transform;
        }
    }
}

検証結果

GameObject

スクリーンショット 2024-08-04 213215.png

Transform

スクリーンショット 2024-08-04 213254.png

どちらも Component.get_xx という Unity内部の処理がアクセスごとに呼び出されており、キャッシュする方が速いことがわかります。

まとめ

gameObject や transform に頻繁にアクセスする場合はキャッシュしたほうがいい

実際には Update で 10000回もアクセスすることはないとおもいますが、Linq や自作の Manager クラス等からアクセスすることが多々あると思うので、キャッシュしてプロパティとして公開するのがいいと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?