unity3d訪問遊戲對象組件

訪問遊戲對象組件

經過獲取組件修改

using UnityEnine;
using System.Collections;
public class Myclass:MonoBehaviour{
    void Update(){
        transform.Translate(1, 0, 0);
        //經過GetComponent<X>()獲取當前遊戲對象上的X組件
        GetComponent<Transform>().Translate(1, 0, 0);
    }}

經過獲取組件修改(腳本Script組件)

using UnityEnine;
using System.Collections;
public class Myclass:MonoBehaviour{
    void Update(){
        //經過GetComponent<X>()獲取當前遊戲對象上的X腳本組件
        HelloWorld hw = GetComponent<HelloWorld>();
        hw.sayHello();//調用該腳本上的sayHello()函數
    }}

由父組件獲取子組件

using UnityEnine;
using System.Collections;
public class Myclass:MonoBehaviour{
    void Update(){
        //經過獲取Transform組件來找到名爲"hand"的子對象
        transform.Find("hand").Translate(0, 0, 1);
    }}

由子組件獲取父組件

using UnityEnine;
using System.Collections;
public class Myclass:MonoBehaviour{
    void Update(){
        //經過獲取Transform組件來找到父對象
        transform.parent.Translate(0, 0, 1);
    }}

由遊戲對象名稱(標籤)獲取

//**當tag包含多個對象時,會獲取到最後讀取的那個對象**
using UnityEnine;
using System.Collections;
public class Myclass:MonoBehaviour{
    void Start(){
        //獲取名稱爲"gamename"的遊戲對象
        GameObject name = GameObject.Find("gamename");
        name.transform.Translate(0, 0, 1);
        //獲取標籤爲"gametag"的遊戲對象
        GameObject tag = GameObject.FindWithTag("gametag");
        teg.GetComponent<Test>().doSomething();
    }}
相關文章
相關標籤/搜索