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 !");
}文章来自:http://blog.csdn.net/xiaxiang123/article/details/41217827