1. 程式人生 > >unity3d常用的遊戲物件引用技巧

unity3d常用的遊戲物件引用技巧

常用引用技巧

1.   當要獲取某類標籤名為“car”的遊戲物件:

privateGameObject[] cars;//宣告汽車遊戲物件陣列

                   cars = GameObject.FindGameObjectsWithTag("car");//找到Tagcar的所有遊戲物件

foreach(GameObject car in cars) {//遍歷汽車陣列

                            car.transform.RotateAround(Vector3.up,Time.deltaTime *speed);//讓所有的汽車繞Y軸自轉

                   }

2.   全域性變數容器使用PlayerPrefs

PlayerPrefs.SetInt("music",musicIndex%2 + 1);//設定music

if(PlayerPrefs.GetInt("music") != 1 &&!GetComponent<AudioSource>().isPlaying) {//music值不為2,且音樂沒有播放

                            GetComponent<AudioSource>().Play();//播放音樂

           }

3.   限制滑鼠在某一個區域運動,關聯螢幕的座標,與攝像頭無關:

4.       using UnityEngine;

5.       usingSystem.Collections;

6.      

7.       publicclassTest : MonoBehaviour {

8.      

9.       // Use this for initialization

10.    publicGameObject test;

11.    privatefloat horizR, vertR;//當前螢幕與預設螢幕寬、高比

12.    void Start () {

13.            test.transform.position =

newVector3(0,0,1);//限制區域z=1

14.   

15.    }

16.   

17.    // Update is called once per frame

18.    void Update () {

19.            horizR = Input.mousePosition.x / Screen.width;

20.            vertR = Input.mousePosition.y / Screen.height;

21.            test.transform.position = newVector3(horizR *100-50,vertR * 50-25,1);//區域長度為100,寬度為50,因此區域的左下角座標為(-50-25, 1

22.   

23.    }

24. }

歡迎大家評論和交流!