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. }


欢迎大家评论和交流!

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值