组件访问是我们常用的API,访问的方式大概有以下三种:GetComponent(“组件名”)、GetComponent()、GetComponent(typeof(组件名称))。测试脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Author:W
* 获取组件的方法的性能对比
*/
public class GetComTest : MonoBehaviour {
private int numTests = 1000000;
private Light light;
// Use this for initialization
void Start () {
Test();
}
private void Test()
{
//通过GetComponent(string)获取组件
using (new ScrptProcessTimer("GetComponent(string)", numTests))
{
for (int i = 0; i < numTests; i++)
{
light = (Light)GetComponent("Light");
}
}
//通过GetComponent<T>获取组件
using (new ScrptProcessTimer("GetComponent<T>", numTests))
{
for (int i = 0; i < numTests; i++)
{
light = GetComponent<Light>();
}
}
//通过GetComponent(typeof())
using (new ScrptProcessTimer("GetComponent(typeof())", numTests))
{
for (int i = 0; i < numTests; i++)
{
light = (Light)GetComponent(typeof(Light));
}
}
}
// Update is called once per frame
void Update () {
}
}
运行结果如下:
由此得出结论:我们在实际项目中最好使用GetComponent()来获取组件。当然对于一般的项目来说,用3种方式也感受不出来差别,如果你有追求精益求精的态度时,当然会选择最好的啦!