unity 抓取物件(GameObject)和元件(Component)

unity 抓取物件(GameObject)和元件(Component)

使用 unity 開發遊戲時,往往需要在程式( C# Script )中表達某個遊戲物件或元件。例如有一個 script 掛在 A 物件,但你卻想要在這個 script 寫程式控制 B 物件,這時候就得懂得抓取物件才行。以下列舉一些常用的方法。 ● 抓取物件(GameObject) GameObject.Find("場景中的物件名稱"); 例如要旋轉場景中名為 kitty 的物件: GameObject.Find("kitty").transform.Rotate( 0, 2, 0 ); GameObject.Find 無法抓取原本不在場景中或未啟用(active為false)的物件。 若要取得這類物件,就先在 script 中 public GameObject myObj; 然後到 Inspector 面板為 public 變數指定物件。(例如從 Project 面板把 prefab 拉進去) ◎ 抓取 tag 物件 GameObject[] myObjArray; myObjArray = GameObject.FindGameObjectsWithTag("foo"); // 所有 tag 為 foo 的物件,都會被抓出來存到變數(陣列) myObjArray 中。 可參閱「unity Array 陣列資料存取」這篇文章。 ◎ 抓取父物件 transform.parent.gameObject; ◎ 抓取子物件 ※ 只包含下一層級物體,不含孫輩以下 transform.GetChild(2).gameObject; // 抓取第 3 個子物體(索引號是從 0 開始),可透過 transform.childCount 取得子物體的數量。 ● 抓取元件(Component) GetComponent<元件類型>(); 例如要對 Rigidbody 元件使用 AddForce 方法: GetComponent().AddForce( 0, 0, 5 ); 除了 transform 可以直接打,其他元件都要用 GetComponent 去抓。 ◎ 抓取所有子物件(含孫輩以下)的元件 Component[] rdrs = yourGameObject.GetComponentsInChildren( typeof(Renderer), true ); foreach (Renderer _renderer in rdrs){ _renderer.enabled = false; } // 停用所有子物體的 Mesh Renderer 元件 為了效能考量,不要在 Update 中重複抓取物件或元件,而是在 Start 中抓取一次儲存到變數中。例如: GameObject box; Rigidbody box_rb; void Start () { box = GameObject.Find("Cube"); box_rb = box.GetComponent(); }建議延伸閱讀: >>

unity C# 語法教學入門 >>

Unity Script 常用語法教學(unity課程入門學習筆記)>>

如何在家學習英文?英文線上課程平台,聽說讀寫一把抓!

相关文章

将联系人导入 iPhone 的 11 种方法 [完整指南]
365bet软件下

将联系人导入 iPhone 的 11 种方法 [完整指南]

⌛ 07-10 👁️‍🗨️ 7657
江苏十三城特色螃蟹图鉴
365365bet官

江苏十三城特色螃蟹图鉴

⌛ 07-12 👁️‍🗨️ 749
斗鱼直播进入主播鱼吧的方法
365365bet官

斗鱼直播进入主播鱼吧的方法

⌛ 07-08 👁️‍🗨️ 9401