概要
using UnityEngine; internal sealed class Player : MonoBehaviour { private static TagHandle? m_enemyTagHandle; private void OnTriggerEnter2D( Collider2D other ) { m_enemyTagHandle ??= TagHandle.GetExistingTag( "Enemy" ); if ( other.CompareTag( m_enemyTagHandle.Value ) ) { } } }
Unity 2023.2.0f1 から CompareTag に TagHandle を渡せるようになり、
string よりも TagHandle を使う方が処理が速く終わるようになった。
(Shader.PropertyToID みたいな感じ。)
検証
using System.Diagnostics; using UnityEngine; using Debug = UnityEngine.Debug; public sealed class Example : MonoBehaviour { public int m_count = 100000000; private void Awake() { { var sw = Stopwatch.StartNew(); for ( var i = 0; i < m_count; i++ ) { if ( CompareTag( "Player" ) ) { } } Debug.Log( sw.Elapsed.TotalSeconds ); } { var sw = Stopwatch.StartNew(); var tagHandle = TagHandle.GetExistingTag( "Player" ); for ( var i = 0; i < m_count; i++ ) { if ( CompareTag( tagHandle ) ) { } } Debug.Log( sw.Elapsed.TotalSeconds ); } } }
| 項目 | 処理にかかった時間 |
|---|---|
| string | 7.6 秒 |
| TagHandle | 2.8 秒 |