Unity3D如何获取GameObject上的Component

获取Component方式

1.直接将脚本挂载到 Light上,可以直接getComponent方式获取。

[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Test : MonoBehaviour {  
  6.   
  7.     GameObject go;  
  8.     Light light;  
  9.   
  10.     // Use this for initialization  
  11.     void Start () {  
  12.         go = new GameObject("name");  
  13.   
  14.         //脚本挂载在Directional Light下,获取light方式  
  15.         light = GetComponent();  
  16.   
  17.         light.color = Color.green;  
  18.   
  19.     }  
  20.       
  21.     // Update is called once per frame  
  22.     void Update () {  
  23.           
  24.     }  
  25. }  
2.挂载在其他GameObject上,获取Light,可将脚本Light设置为public属性,脚本上拖动相应组件到上面

[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Test : MonoBehaviour {  
  6.   
  7.     GameObject go;  
  8.     public Light light;  
  9.   
  10.     // Use this for initialization  
  11.     void Start () {  
  12.         go = new GameObject("name");  
  13.   
  14.         light.color = Color.green;  
  15.   
  16.     }  
  17.       
  18.     // Update is called once per frame  
  19.     void Update () {  
  20.           
  21.     }  
  22. }  

3.先找到对应GameObject,再获取组件


[csharp]  view plain  copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Test : MonoBehaviour {  
  6.   
  7.     GameObject go;  
  8.     GameObject goLight;  
  9.   
  10.     Light light;  
  11.   
  12.     // Use this for initialization  
  13.     void Start () {  
  14.         go = new GameObject("name");  
  15.         goLight = "color:#ff0000;">GameObject.Find("gameobject'name");//遍历Hierarchy下面全部的对象  
  16.         light = goLight.GetComponent();  
  17.         light.color = Color.green;  
  18.   
  19.     }  
  20.       
  21.     // Update is called once per frame  
  22.     void Update () {  
  23.           
  24.     }  
  25. }  


注意:如果场景下包含相同的对象名字,则需要给GameObject.Find()方法可以传入绝对路径。栗子:Find(gm/gm1/Light)


[csharp]  view plain  copy
  1. ///   
  2. /// 寻找物体  
  3. ///   
  4. /// 作为父物体的transform  
  5. /// 寻找的物体的名称  
  6. /// 找到的物体  
  7. void FindChild(Transform trans,string findname,ref Transform _trans)  
  8. {  
  9.   
  10.     if(trans.name.Equals(findname)){  
  11.         _trans = trans.transform;  
  12.         return;  
  13.     }  
  14.   
  15.     if(trans.childCount != 0){  
  16.         for (int i = 0, len = trans.childCount; i < len; i++)  
  17.         {  
  18.             FindChild(trans.GetChild(i),findname,ref _trans);  
  19.         }  
  20.     }  
  21.   
  22. }  

你可能感兴趣的:(Unity3D脚本)