1. 程式人生 > >Unity3D常用代碼集合

Unity3D常用代碼集合

double tint lac level bre them state 5.0 pla

1、基本碰撞檢測代碼

function OnCollisionEnter(theCollision : Collision){

if(theCollision.gameObject.name == "Floor"){

Debug.Log("Hit the floor");

}else if(theCollision.gameObject.name == "Wall"){

Debug.Log("Hit the wall");

}

}

2、檢測輸入

function Update () {

if(Input.GetButtonUp("Jump")){

Debug.Log("We Have Hit the Space Bar!");

}

}
3、銷毀對象

function Start () {

Destroy(gameObject.Find("Box"), 3);

}
4、實例來創建對象

//Simple Instantiation of a Prefab at Start


var thePrefab : GameObject;

function Start () {

var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);

}
把代碼拖入到空GameJect上,然後把Prefab拖入到公共變量上。
5、簡易定時器

var myTimer : float = 5.0;

function Update () {

if(myTimer > 0){

myTimer -= Time.deltaTime;

}

if(myTimer <= 0){

Debug.Log("GAME OVER");

}

}
6、物體在屏幕上移動

var speed : float = 5.0;

function Update () {

transform.Translate(Vector3(0,0,speed) * Time.deltaTime);

}
7、鋼體向目標處移動

//Basic force to move a rigidbody object

var power : float = 500.0;

function Start () {

rigidbody.AddForce(Vector3(0,0,power));

}
8、碰撞然後轉到下一場景

function OnCollisionEnter (Collision : Collision) {

if(gameObject.name == "Floor"){

Application.LoadLevel(myLevel);

}

}
floor---被動碰撞的的綱體
把代碼拉到主動綱體上,然後場景設置:file----build seting----對話框,然後把當前場景拖裏,然後把下一場景拖裏,測試OK!

09

Debug.Log("Hit the wall");

10

11

}

12

13

}

Unity3D常用代碼集合