QuickFindChildAndComponent (Unity快速找孩子的组件)

来源:互联网 发布:300mw机组造价数据 编辑:程序博客网 时间:2024/06/05 17:49
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;


public class QuickFindChildAndComponent : MonoBehaviour {


    // Use this for initialization
    void Start()
    {
        Debug.Log(ToHaveComponents(transform, "C", typeof(Rigidbody)));
        Debug.Log(ToHaveComponents(transform, "D", typeof(Text)));


    }


    public Component ToHaveComponents(Transform b, string name, Type type)
    {
        Transform t = FindTransform(b, name);


        return t.GetComponent(type.Name);
    }


    public Transform FindTransform(Transform b, string name)
    {
        foreach (Transform item in b)
        {
            if (item.name == name)
            {
                return item;
            }
            else
            {
                if (item.childCount > 0)
                {
                    return FindTransform(item, name);
                }
            }
        }
        return null;
    }
}
原创粉丝点击