UPL5-2——脚本获取相关

用最快方式获取组件

Unity 中获取组件得到方式主要是通过调用 GetComponent 方法,它提供了几种重载:

  1. Component GetComponent(Type type):通过类型的Type获取
  2. T GetComponent<T>():通过泛型获取
  3. Component GetComponent(string type):通过字符串获取

在日常开发时,如果要获取组件,一定要选中速度最快的,也就是通过泛型的方式去获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
IEnumerator Test()
{
uint nums = 1000000;
yield return null;

using (new CodeTimer("GetComponent(string type)", nums))
{
for (int i = 0; i < nums; i++)
{
test = this.GetComponent("GetTest") as GetTest;
}
}
yield return null;

using (new CodeTimer("GetComponent(Type type)", nums))
{
for (int i = 0; i < nums; i++)
{
test = this.GetComponent(typeof(GetTest)) as GetTest;
}
}
yield return null;

using (new CodeTimer("GetComponent<T>()", nums))
{
for (int i = 0; i < nums; i++)
{
test = this.GetComponent<GetTest>();
}
}
yield return null;
}

image

对频繁调用的组件应缓存组件引用

在 Unity 中反复获取一个组件是一种常见错误,对于一些常见的组件,我们不应该每次都重复的去获取
即使使用最快的泛型获取方式,多多少少还是会带来一些消耗(积少成多也是不菲的开销)
因此我们应该把常用的内容缓存下来,下次使用时不用寻找直接用,这样可以给我带来性能的提升