iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1100319 自動抓取GameObject或Component屬性與應用
by 黃國哲 2021-03-19 14:17:19, 回應(0), 人氣(3462)

一、自動尋找並載入GameObject 

大致有以下 Find類型

GameObject.Find("name");  //用名字尋找GameObject子物件
GameObject.FindWithTag("Tag");  //用Tag尋找物件(同Tag時只會選第一個物件)
GameObject.FindGameObjectsWithTag("Tag");  //用Tag尋找物件(全部物件)
Resources.FindObjectsOfTypeAll(typeof(colliderTest)) //尋找Objects


1.舉例當目標為GameObject時
(以 GameObject.Find("name"); 為例子)

public GameObject 目標1 ; //先公開宣告 目標1,該屬性是GameObject

//在Start () 裡寫入下列腳本作為開始執行的第一個動作
目標1 = GameObject.Find("目標 GameObject的名字") ; 
//會自動把場景裡面要拿來當目標的GameObject自動填入public裡面



2.舉例當目標為UI中的Text時
(以 GameObject.Find("name"); 為例子)

public Text 目標1 ; //先公開宣告 目標1 ,該屬性是Text

//在Start () 裡寫入下列腳本作為開始執行的第一個動作
目標1 = GameObject.Find("目標 Text的名字").GetComponent<Text>() ; 
//會自動把場景裡面要拿來當目標的Text自動填入public裡面


二、自動尋找並載入Component

GetComponent<Transform> ().position.x ;

透過這個寫法可以抓到該GameObject裡面的Transform組件裡的變數position.x ,也就是x軸的值

應用如下

public float posvalue ; //宣告posvalue為浮點數

posvalue = GetComponent<Transform> ().position.x ; 
//其值為掛上這個腳本的GameObject的x軸值
也可以抓取其他物件GameObject的值
結構變成:
GameObject.GetComponent<Transform> ().position.x
把語法調整成:

public float posvalue ; 
public GameObject Target ;


posvalue = Target.GetComponent<Transform> ().position.x ; 







回應