Unity3d修煉之路:載入一個預制體,然后為該對象加入組件,然后查找對象,得到組件。


#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 !");
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM