Unity Find GetComponent

来源:互联网 发布:淘宝小二判定错误申诉 编辑:程序博客网 时间:2024/06/04 22:47
Unity提供了多种获得物体的方法,其中Find是效率最低的一种,我记得文档中应该有提到过尽量少用。

最快的获取物体的方法是直接引用:
  1. public GameObject select;

  2. void Update()
  3. {
  4.     // do sth with select
  5. }
复制代码
然后C#的GetComponent<T>系列函数应该是仅次于直接引用:GetComponent<T>; GetComponentInChildren<T>; GetComponentsInChildren<T>
  1. private AudioSource sfx;

  2. void Start()
  3. {
  4.     sfx = GetComponentInChildren<AudioSource>();
  5. }
复制代码
然后是FindWithTag; FindGameObjectsWithTag。虽然效率不及前者,但是通过Tag寻找物体是游戏中常用的手段,而且Unity内置了Tag系统,用起来很方便。

如果是在其子物体中寻找某一个类型(Class)Component,GetComponentInChildren<T>是最佳选择,如果是在整个场景中搜寻某一种GameObject,基于FindWithTag从实用性和速度上都是很好的选择。
0 0
原创粉丝点击