Unity 常用代码

关注专栏,持续更新哦

教程总目录

输入相关

检测键盘输入

// 两种,视情况而定用哪个
// 每帧都触发
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_EDITOR
	UnityEditor.EditorApplication.isPlaying = false;
#else
	Application.Quit();
#endif

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/106950067