Unity腳本:GetComponent 取得元件
- 詳細內容
- 分類:Unity
- 發佈:2014-05-09, 週五 09:55
- 點擊數:3506
Unity腳本:GetComponent 取得元件
GetComponent 方法可以在遊戲物件(GameObject)或是元件(Component)裡找到。
GameObject.GetComponent:
1. GetComponent(type: Type): Component;
GetComponent會傳回類行為type的元件,若是找不到該元件,則傳回null。
GetComponent 可以取得內建元件以及腳本元件。
GetComponent 是取得其他元件的主要方法,對Javascript而言,腳本的類型(type)就是腳本本身的名字。
function Start () {
var curTransform : Transform;
curTransform = gameObject.GetComponent(Transform);
// 上面一行程式碼跟下面這行程式碼是一樣的,這是因為Transform元件太常用了,
// 每次都要GetComponent並不方便,所以Unity給了一個方便的寫法。
curTransform = gameObject.transform;
}
function Update () {
// 存取在相同物件下其他腳本的公開變數以及函式
// (ScriptName 就是avascript檔案的名稱)
var other : ScriptName = gameObject.GetComponent(ScriptName);
// 呼叫腳本中的函式來做一些事
other.DoSomething ();
// 在other腳本實例中的變數
other.someVariable = 5;
}
2. GetComponent(): T;
GetComponent 的泛型版本。
3.GetComponent(type: string): Component;
使用字串來取得元件。不過,使用類型來取得元件會比使用字串來取得元件有更好的效能。
但是有時候會沒辦法取得類型,譬如說在Javascript中要取得C#寫的腳本。
這種情況下可以用腳本名字字串來代替類型名稱。
function Update () {
// 存取在相同物件下其他腳本的公開變數以及函式
// (ScriptName 就是avascript檔案的名稱)
var other : ScriptName;
other = gameObject.GetComponent("ScriptName");
// 呼叫腳本中的函式來做一些事
other.DoSomething ();
// 在other腳本實例中的變數
other.someVariable = 5;
}
參考:http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
參考:http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
官網教學:
按個讚!~支持本站!~
FB推薦載入中