Unity 常用代码
关注专栏,持续更新哦
教程总目录
文章目录
- 输入相关
- 检测键盘输入
- 检测鼠标输入
- 向量相关
- 获取方向
- 获取两个点之间的向量
- 获取距离
- Rigidbody相关
- 设置速度
- 施加力
- 移动
- 旋转
- Transform相关
- 移动旋转
- 旋转偏差角
- 获取位置
- 对象相关
- 摧毁对象
- 产生对象
- 获取对象标签
- 通过名字查找对象
- 通过标签查找对象
- 获取子对象
- 获取父对象
- 其它
- 产生随机数
- 一帧所需时间
- 定时操作
- 音乐
- 天空
- 射线
- 修改不透明度
- 摄像机背景色
- 退出游戏
输入相关
检测键盘输入
// 两种,视情况而定用哪个
// 每帧都触发
if(Input.GetKey(KeyCode.I/Space/LeftArrow))
// 按下的帧触发
if(Input.GetKey(KeyCode.I/Space/LeftArrow))
检测鼠标输入
if(Input.GetMouseButtonDown(0))
向量相关
获取方向
Input.GetAxis("Vertical/Horizontal/Mouse X/Mouse Y")
获取两个点之间的向量
Vector3.MoveTowards(transform.position, startPoint.position, speed * Time.deltaTime);
获取距离
Vector3.Distance( V3,V3)
Rigidbody相关
设置速度
this.GetComponent<Rigidbody>().velocity = new Vector3(x,y,z)
施加力
this.GetComponent<Rigidbody>().AddForce(Vector3.up * force, ForceMode.Force);
移动
this.GetComponent<Rigidbody>().MovePosition
旋转
this.GetComponent<Rigidbody>().MoveRotation(this.transform.rotation * deltaRotation);
Transform相关
移动旋转
this.transform.Translate(x,y,z)/Rotate(x,y,z)
旋转偏差角
Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
获取位置
transform.position.y
对象相关
摧毁对象
Destroy(this.gameObject)
产生对象
Instantiate (GameObject obj, Vector3 v, Quaternion.identity)
获取对象标签
GameObject.tag
通过名字查找对象
GameObject.Find("name")
通过标签查找对象
GameObject.FindGameObjectWithTag("tag")
获取子对象
transform.Find("Son Name")
获取父对象
transform.parent
其它
产生随机数
Random.Range (-10, 10)
一帧所需时间
Time.deltaTime
定时操作
float timer -= Time.deltaTime
音乐
AudioSource=this.GetComponent<AudioSource>()
if (!AudioSource.isPlaying) {AudioSource.clip = AudioClip ;AudioSource.Play(); }
天空
RenderSettings.skybox=...
camera1.transform.GetComponent<Skybox>().material=...
射线
Ray rays = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(rays.origin, rays.direction * 100, Color.yellow);
RaycastHit hit;
if (Physics.Raycast(rays, out hit)){ currentObject = hit.transform;}
修改不透明度
public static void SetOpaquenessOfGameObject(GameObject obj,float a)
{Color c = obj.GetComponent<SpriteRenderer>().material.color;c.a = a;obj.GetComponent<SpriteRenderer>().material.color = c;
}
摄像机背景色
mainCamera.backgroundColor = Color.Lerp(mainCamera.backgroundColor, Color.red, speed * Time.deltaTime); mainCamera.orthographicSize = Mathf.Lerp(mainCamera.orthographicSize, 4, speed * Time.deltaTime);
退出游戏
#if UNITY_EDITORUnityEditor.EditorApplication.isPlaying = false;
#elseApplication.Quit();
#endif
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
