获取Component方式
1.直接将脚本挂载到 Light上,可以直接getComponent方式获取。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Test : MonoBehaviour {
- GameObject go;
- Light light;
- // Use this for initialization
- void Start () {
- go = new GameObject("name");
- //脚本挂载在Directional Light下,获取light方式
- light = GetComponent<Light>();
- light.color = Color.green;
- }
- // Update is called once per frame
- void Update () {
- }
- }
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Test : MonoBehaviour {
- GameObject go;
- public Light light;
- // Use this for initialization
- void Start () {
- go = new GameObject("name");
- light.color = Color.green;
- }
- // Update is called once per frame
- void Update () {
- }
- }
3.先找到对应GameObject,再获取组件
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Test : MonoBehaviour {
- GameObject go;
- GameObject goLight;
- Light light;
- // Use this for initialization
- void Start () {
- go = new GameObject("name");
- goLight = <span style="color:#ff0000;">GameObject.Find</span>("gameobject'name");//遍历Hierarchy下面全部的对象
- light = goLight.GetComponent<Light>();
- light.color = Color.green;
- }
- // Update is called once per frame
- void Update () {
- }
- }
注意:如果场景下包含相同的对象名字,则需要给GameObject.Find()方法可以传入绝对路径。栗子:Find(gm/gm1/Light)
- /// <summary>
- /// 寻找物体
- /// </summary>
- /// <param name="trans">作为父物体的transform</param>
- /// <param name="findname">寻找的物体的名称</param>
- /// <param name="_trans">找到的物体</param>
- void FindChild(Transform trans,string findname,ref Transform _trans)
- {
- if(trans.name.Equals(findname)){
- _trans = trans.transform;
- return;
- }
- if(trans.childCount != 0){
- for (int i = 0, len = trans.childCount; i < len; i++)
- {
- FindChild(trans.GetChild(i),findname,ref _trans);
- }
- }
- }