天天看點

【 Unity GameObject類 】GameObject.GetComponent 控制元件另外還有幾個相似的類方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityGameOject : MonoBehaviour
{

    void Start()
    {
        //擷取對象元件(控制元件)
        ///下面的這兩種方法都是一樣的
        ///通過建立一個空元件,并引用從對象中獲得的元件
        ///進而得以控制對象的元件
        ///
        ///如果對象中沒有這個元件,GetComponent會傳回null


        ///元件類型 元件對象名 = 對象名.GetComponent(typeof(元件類型)) as 元件類型
        Transform xyz = gameObject.GetComponent(typeof(Transform)) as Transform ;


        ///元件類型 元件對象名 = 對象名.GetComponent<元件類型>();
        Rigidbody rb = gameObject.GetComponent<Rigidbody>();

        
    }
}

           

另外還有幾個相似的類方法

GetComponentInChildren	//向下搜尋子元件,并傳回(深度優先)

GetComponentInParent	//向上搜尋父級元件,并傳回

GetComponents	//傳回全部元件
	//示例
	 Transform [] xyz;
     xyz = GetComponents(typeof(Transform ));

GetComponentsInChildren	//向下搜尋子元件,并全部傳回(需要建立元件數值[])
	//示例
	 Transform [] xyz;
     xyz = GetComponentsInChildren(typeof(Transform ));
     
GetComponentsInParent //向上搜尋父級元件,并全部傳回(需要建立元件數值[])
	//示例
	 Transform [] xyz;
     xyz = GetComponentsInPrent(typeof(Transform ));