Unity-2,获取同一个脚本下面的对象

 1   void Start()
 2     {
 3         //所有对象挂载了相同的脚本
 4 
 5         Lesson1 t1 = this.GetComponent("Lesson1") as Lesson1;
 6         print(t1);
 7 
 8         Lesson1 t2 = this.GetComponent(typeof(Lesson1)) as Lesson1;
 9         print(t2);
10 
11         Lesson1 t3 = this.GetComponent<Lesson1>();
12         print(t3);                      
13     }

 

2,有多少个对象挂载了这个脚本

 

 1 public Lesson1 ls1;
 2 
 3     void Start()
 4     {
 5         
 6         //有多少个对象挂载了这个脚本
 7         Lesson1[] a1 = this.GetComponents<Lesson1>();
 8 
 9         print(a1.Length);
10         
11     }

 

3,获取子对象的脚本

 1 public Lesson1 ls1;
 2 
 3     void Start()
 4     {
 5 
 6         //这个脚本下面有多少个子对象挂载了这个脚本(包括父对象本身)[失活的对象是不会找到的,如果加上True,即使失活了,也会去查找]
 7         Lesson1 a1 = this.GetComponentInChildren<Lesson1>();
 8         Lesson1 a1 = this.GetComponentInChildren<Lesson1>(true);
 9  print(a1.name); 10 11 }

 

posted @ 2021-07-25 18:31  青梨  阅读(272)  评论(0编辑  收藏  举报