Unity中常用方法
1.基础
//初始化引入
[RequireComponent(typeof(BoxCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]//游戏帧率设置 60帧Application.targetFrameRate = 60;//获取物体对象
//获取到当前物体(根据名称,也可以根据路径)GameObject go= GameObject.Find("红旗");GameObject go = this.transform.GetChild(0).gameObject; //根据下标GameObject go= Resources.LoadAll<GameObject>("preform/Enemys");//根据目录结构查找Resources目录下面//物体位置世界位置/本地位置Vector3 vector3 = gameObject.transform.position;Vector3 vector3 = gameObject.transform.localPosition;//复制物体AudioSource music = this.GetComponent<AudioSource>();Rigidbody2D rb = this.GetComponent<Rigidbody2D>();Translate tr= this.GetComponent<Translate>();//挂载脚本
gameObject.AddComponent<BulletCol>();//当前鼠标点击
Input.GetMouseButtonDown(0)
2.方法
1.物体移动Translate物体旋转Rotate
//物体移动 Translate(x, y, z, 相对)Self 相对自己,Word相对世界
this.transform.Translate(0, 0, 每秒运行长度, Space.Self);//物体旋转 Rotate(x, y, z, 相对)Self 相对自己,Word相对世界
this.transform.Rotate(0, 速度 * Time.deltaTime, 0, Space.Self);//父物体旋转 Rotate(x, y, z, 相对)Self 相对自己,Word相对世界
this.transform.parent.Rotate(0, 速度 * Time.deltaTime, 0, Space.Self);
2.朝向物体移动LookAt
//让当前物体看向红旗 把物体z轴转向目标LookAt(transform);
this.transform.LookAt(GameObject.transform);
3.播放音乐
public AudioClip[] acp;public void playMusic(){int index = Random.Range(0, acp.Length);AudioSource ast = GetComponent<AudioSource>();ast.clip = this.acp[index];ast.Play();ast.Stop();}
4.赋予初始速度(刚体)Rigidbody2D
Rigidbody2D rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(x,y);//x/y 为多少速度为多少
5.本地坐标转世界坐标
Vector3 targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
6.动画处理传送门
7.摄像机跟随玩家
3.函数
定时函数
InvokeRepeating("射击", 1, 2); // 等待1秒后每2秒吊用一次射击的方法。
IsInvoking("射击") 判断该函数是否被调用 如果没有在调用
CancelInvoke("射击") 取消被调用
预制体
//实例化预制体, Instantiate(预制体,位置,旋转,父节点)
Instantiate(bg,new Vector3(0f,0f,0f),Quaternion.identity,this.transform);
图像轮动
//_MainTex写死,Vector(x,y); Time.time/5沿着X轴5秒轮动一次
this.GetComponent<Renderer>().material.SetTextureOffset("_MainTex",new Vector2(Time.time/5,0));
4.生命周期
void Awake(){} //最早时调用,一般可以在此实现单例模式(未激活的组件也会被调用)
void OnEnable(){} //组件激活后调用,在awake()后调用一次
void Start(){} //在update()之前调用一次,在onEnable之后调用,可以再次设置一些初始值。(未激活的组件不会被调用)
void FixedUpdate(){}//固定频率调用方法,每次调用与上次调用的时间间隔相同
void Update(){} //帧率调用法,每帧调用一次,每次调用与上一次调用的时间间隔不相同
void LateUpdate(){} //在udate()每调用完一次后,紧跟着调用一次
void OnDisable(){} //与onEnable相反,组件未激活时调用
void OnDestroy(){} //被销毁后调用一次