新建脚本
using System.Collections;
using UnityEngine;
public class TagTesting : MonoBehaviour
{
const int numberOfTests = 1000000;
GameObject go;
// Start is called before the first frame update
void Start()
{
go = new GameObject();
}
void PerformTagEquals()
{
for (int i = 0; i < numberOfTests; i++)
{
if(go.tag == "Player")
{
}
}
}
void PerformCompareTag()
{
for (int i = 0; i < numberOfTests; i++)
{
if(go.CompareTag("Player"))
{
}
}
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
PerformTagEquals();
PerformCompareTag();
}
}
}
上面脚本中,当按下空格键的时候,PerformTagEquals()和PerformCompareTag()会执行,在各自的方法内部执行1000000此循环,我们来看一下这两种比较方式的耗时情况。
在Unity中场景中,新建一个空GameObject,将脚本挂载上去,运行。
打开Profiler, 按下空格键,然后暂停游戏,下面是Profiler的截图:
我们可以看到:
- PerformTagEquals() 耗时483.53毫秒,而且产生了36.2MB的GC
- PerformCompareTag() 耗时158.84毫秒,而且没有产生GC
总结
根据tag来查找游戏对象是开发种常用的方法,从上面的测试种可以看出,应该使用Unity提供的CompareTag方法来查找,不产生GC,性能更好。