facebook twitter hatena line email

Unity/負荷軽減/GameObjectFind

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

GameObject.FindとGetCompornentの負荷検証

実際に測ったらGameObject.Findはやばいけど、GetCompornent側は差がなかった。Updateに40個ほど用意したもので検証。

GC Allocの数値比較

  • GameObject.FindとGetCompornentの両方:4.1KB
  • GetCompornentのみ:1.4KB
  • 両方なし:1.4KB

GameObject.FindとGetCompornentの両方

public class FindCompornentScene : MonoBehaviour
{
    int num = 0;
    void Start()
    {
        for (int i = 1; i <= 40; i++)
        {
            GameObject prefab = (GameObject)Resources.Load("Text");
            Vector3 position = new Vector3(0, 0, 0);
            GameObject obj = Instantiate(prefab, position, Quaternion.identity, GameObject.Find("Canvas").transform);

            obj.transform.localPosition = new Vector3((int)((i - 1) / 10) * 200 - 200, i % 10 * 100 - 400, 0);
            obj.name = "Text" + i;
        }
    }
    void Update()
    {
        for (int i = 1; i <= 40; i++)
        {
            GameObject.Find("Text" + i).GetComponent<Text>().text = num.ToString();
            num++;
        }
    }
}

GetCompornentのみ

public class FindCompornentGetComponentScene : MonoBehaviour
{
    List<GameObject> texts;
    int num = 0;
    void Start()
    {
        texts = new List<GameObject>();
        for (int i = 1; i <= 40; i++)
        {
            GameObject prefab = (GameObject)Resources.Load("Text");
            Vector3 position = new Vector3(0, 0, 0);
            GameObject obj = Instantiate(prefab, position, Quaternion.identity, GameObject.Find("Canvas").transform);

            obj.transform.localPosition = new Vector3((int)((i - 1) / 10) * 200 - 200, i % 10 * 100 - 400, 0);
            obj.name = "Text" + i;
        }

        for (int i = 1; i <= 40; i++)
        {
            texts.Add(GameObject.Find("Text" + i));
        }
    }
    void Update()
    {
        for (int i = 1; i <= 40; i++)
        {
            texts[i - 1].GetComponent<Text>().text = num.ToString();
            num++;
        }
    }
}

両方なし

public class FindCompornentNotScene : MonoBehaviour
{
    List<Text> texts;
    int num = 0;
    void Start()
    {
        texts = new List<Text>();
        for (int i = 1; i <= 40; i++)
        {
            GameObject prefab = (GameObject)Resources.Load("Text");
            Vector3 position = new Vector3(0, 0, 0);
            GameObject obj = Instantiate(prefab, position, Quaternion.identity, GameObject.Find("Canvas").transform);

            obj.transform.localPosition = new Vector3((int)((i - 1) / 10) * 200 - 200, i % 10 * 100 - 400, 0);
            obj.name = "Text" + i;
        }

        for (int i = 1; i <= 40; i++)
        {
            texts.Add(GameObject.Find("Text" + i).GetComponent<Text>());
        }
    }
    void Update()
    {
        for (int i = 1; i <= 40; i++)
        {
            texts[i - 1].text = num.ToString();
            num++;
        }
    }
}