#pragma strict function Awake(){ //載入一個預制體 資源必須在 Resources目錄下 Resources.LoadLoad(); //載入后 必須演示樣例化 GameObject.Instantiate(); //為對象加入組件 AddComponent(); //Find游戲對象 Find(); //Get組件 GetComponent(); var pPrefab : GameObject = Resources.Load("Prefab/Scence",typeof(GameObject)) as GameObject;//載入一個預制體 if(null != pPrefab) { var pPreabInstance : GameObject = GameObject.Instantiate(pPrefab);//演示樣例化 if(null != pPreabInstance) { pPreabInstance.name = "PrefabScence"; var pScript : Prefab_test = pPreabInstance.AddComponent("Prefab_test") as Prefab_test;//為對象加入組件 if(pScript == null) { Debug.Log("Component add error!"); } } else { Debug.Log("Prefab Instance error!"); } } else { Debug.Log("Prefab load error!"); } } function Start(){ var pMyGameObject : GameObject = GameObject.Find("PrefabScence");//Find游戲對象 if(null != pMyGameObject) { var pScript : Prefab_test = pMyGameObject.GetComponent("Prefab_test") as Prefab_test;//Get組件 if(null != pScript) { pScript.DoSomething(); } else { Debug.Log("Get Component error!"); } } else { Debug.Log("Find GameObject error!"); } }
腳本組件的代碼
#pragma strict function Update(){ var fAngle : float= 30.0f; transform.Rotate(transform.up * Time.deltaTime * fAngle); } function DoSomething (){ Debug.Log("wo shi da huai dan !"); }