Unity3D获取GameObject上的Component教程

发表于2018-11-07
评论0 1.18w浏览
游戏开发的过程中可能有时想要去找所有包含某种Component的GameObject,那下面这篇文章就给大家介绍下获取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 () {
	}
}

2、挂载在其他GameObject上,获取Light,可将脚本Light设置为public属性,脚本上拖动相应组件到上面
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 = GameObject.Find("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);
            }
        }
    }

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引