Unity3D如何获取GameObject上的Component

来源:互联网 发布:linux gzip 打包压缩 编辑:程序博客网 时间:2024/05/22 04:45

获取Component方式

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

using System.Collections;using System.Collections.Generic;using UnityEngine;public class Test : MonoBehaviour {    GameObject go;    Light light;// Use this for initializationvoid Start () {        go = new GameObject("name");        //脚本挂载在Directional Light下,获取light方式        light = GetComponent<Light>();        light.color = Color.green;}// Update is called once per framevoid 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 initializationvoid Start () {        go = new GameObject("name");        light.color = Color.green;}// Update is called once per framevoid 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 initializationvoid Start () {        go = new GameObject("name");        goLight = GameObject.Find("gameobject'name");//遍历Hierarchy下面全部的对象        light = goLight.GetComponent<Light>();        light.color = Color.green;}// Update is called once per framevoid 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);            }        }    }


0 0
原创粉丝点击