您的位置:首页 > 移动开发 > Unity3D

Unity3d修炼之路:载入一个预制体,然后为该对象加入组件,然后查找对象,得到组件。

2016-02-27 19:30 465 查看
#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 !");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: