常用引用技巧
1. 当要获取某类标签名为“car”的游戏对象:
privateGameObject[] cars;//声明汽车游戏对象数组
cars = GameObject.FindGameObjectsWithTag("car");//找到Tag为car的所有游戏对象
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. }
欢迎大家评论和交流!