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?

More than 5 years have passed since last update.

【Unity】なぜGetComponentを毎フレーム取得することが推奨されていないのか

Posted at

毎フレームGetComponent<>()

よくGetComponentは毎フレームやることはよろしくないという話を聞きますがなぜダメなのでしょうか?

試してみよう!

今回は二つのScriptを用意しました

片方は先にComponent取得してから10万回Transform.positionにvector(0,0,0)を入れる

C#test.cs
  private void Start()
	{
		Transform t=GetComponent<Transform>();
		for (int i = 0; i < 100000; i++)
		{
			t.position = new Vector3(0,0,0);
                } 
       }

もう片方は10万回GetComponetして10万回Transform.positionにvector(0,0,0)を入れる

C#test2.cs
	private void Start()
	{
		for (int i = 0; i < 100000; i++)
		{
			GetComponent<Transform>().position = new Vector3(0,0,0);
		}
	}

結果

8f265ca3adca739ea0423092d4e3da10.png
2倍近く差が出てるんですけど…
今回は10万回で検証しましたがこれが毎フレーム実行されたとしても2倍近く処理が無駄ってことですね。
仕様上仕方がない理由以外ではUpdateでGetComponentをするこはよろしくなさそうですね。

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?