跳到主要内容

Unity 速查表

编辑器快捷键

变换工具

快捷键功能
Q手型工具(平移视图)
W移动工具
E旋转工具
R缩放工具
T矩形工具
Y变换工具(组合)

视图导航

快捷键功能
鼠标右键拖拽旋转视图
鼠标中键拖拽平移视图
滚轮缩放视图
Alt + 左键拖拽环绕选中对象
F聚焦选中对象
Shift + F锁定视图到选中对象

常用操作

快捷键功能
Ctrl/Cmd + S保存场景
Ctrl/Cmd + Shift + S另存为
Ctrl/Cmd + N新建场景
Ctrl/Cmd + O打开场景
Ctrl/Cmd + Z撤销
Ctrl/Cmd + Shift + Z重做
Ctrl/Cmd + D复制对象
Ctrl/Cmd + Shift + N创建空对象
Delete删除对象
Ctrl/Cmd + P播放/停止
Ctrl/Cmd + Shift + P暂停

MonoBehaviour 生命周期

Awake()        → 脚本实例化时(仅一次)

OnEnable() → 对象启用时

Start() → 第一帧前(仅一次)

FixedUpdate() → 固定时间间隔(物理更新)

Update() → 每帧调用

LateUpdate() → 所有 Update 后

OnDisable() → 对象禁用时

OnDestroy() → 对象销毁时

输入系统

传统 Input

// 键盘
Input.GetKeyDown(KeyCode.Space) // 按下
Input.GetKey(KeyCode.W) // 按住
Input.GetKeyUp(KeyCode.Space) // 松开

// 鼠标
Input.GetMouseButtonDown(0) // 左键按下
Input.GetMouseButton(0) // 左键按住
Input.GetMouseButtonUp(0) // 左键松开
Input.mousePosition // 鼠标位置
Input.GetAxis("Mouse X") // 鼠标移动
Input.GetAxis("Mouse ScrollWheel") // 滚轮

// 虚拟轴
Input.GetAxis("Horizontal") // A/D 或 左右键
Input.GetAxis("Vertical") // W/S 或 上下键
Input.GetAxisRaw("Horizontal") // 无平滑

Transform 操作

// 位置
transform.position // 世界位置
transform.localPosition // 本地位置
transform.Translate(Vector3.forward * speed * Time.deltaTime)

// 旋转
transform.rotation // 四元数旋转
transform.eulerAngles // 欧拉角
transform.Rotate(0, 90, 0)
transform.LookAt(target)

// 缩放
transform.localScale = Vector3.one * 2f

// 父子关系
transform.SetParent(parentTransform)
transform.SetParent(null) // 解除父子

向量操作

// 常用向量
Vector3.zero // (0, 0, 0)
Vector3.one // (1, 1, 1)
Vector3.up // (0, 1, 0)
Vector3.right // (1, 0, 0)
Vector3.forward // (0, 0, 1)

// 向量运算
Vector3.Distance(a, b) // 距离
Vector3.Dot(a, b) // 点积
Vector3.Cross(a, b) // 叉积
Vector3.Lerp(a, b, t) // 线性插值
Vector3.Slerp(a, b, t) // 球面插值
vector.normalized // 单位向量
vector.magnitude // 长度

物理系统

Rigidbody

Rigidbody rb = GetComponent<Rigidbody>();

// 施加力
rb.AddForce(Vector3.up * 10f, ForceMode.Force)
rb.AddForce(Vector3.up * 10f, ForceMode.Impulse)
rb.AddTorque(Vector3.up * 10f)

// 直接设置
rb.velocity = new Vector3(0, 5, 0)
rb.angularVelocity = Vector3.up * 10f
rb.MovePosition(newPosition)
rb.MoveRotation(newRotation)

碰撞检测

// 3D 碰撞
void OnCollisionEnter(Collision collision) { }
void OnCollisionStay(Collision collision) { }
void OnCollisionExit(Collision collision) { }

// 3D 触发器
void OnTriggerEnter(Collider other) { }
void OnTriggerStay(Collider other) { }
void OnTriggerExit(Collider other) { }

// 2D 碰撞
void OnCollisionEnter2D(Collision2D collision) { }
void OnCollisionStay2D(Collision2D collision) { }
void OnCollisionExit2D(Collision2D collision) { }

// 2D 触发器
void OnTriggerEnter2D(Collider2D other) { }
void OnTriggerStay2D(Collider2D other) { }
void OnTriggerExit2D(Collider2D other) { }

射线检测

// 基础射线检测
Ray ray = new Ray(origin, direction);
if (Physics.Raycast(ray, out RaycastHit hit, maxDistance))
{
hit.point; // 击中点
hit.normal; // 法线
hit.collider; // 碰撞器
hit.distance; // 距离
}

// 从相机发射
Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);

// 层遮罩
LayerMask mask = LayerMask.GetMask("Enemy");
Physics.Raycast(ray, out hit, maxDistance, mask);

// 区域检测
Collider[] colliders = Physics.OverlapSphere(center, radius);
Collider[] colliders = Physics.OverlapBox(center, halfExtents);

游戏对象操作

// 创建
GameObject obj = new GameObject("Name");
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
GameObject instance = Instantiate(prefab, position, rotation);

// 销毁
Destroy(gameObject);
Destroy(gameObject, delay);
Destroy(component);

// 查找
GameObject.Find("Name");
GameObject.FindWithTag("Tag");
GameObject.FindGameObjectsWithTag("Tag");
FindObjectOfType<MyScript>();
FindObjectsOfType<MyScript>();

// 激活
gameObject.SetActive(true);
gameObject.SetActive(false);
bool isActive = gameObject.activeInHierarchy;

// 标签和层
gameObject.tag = "Player";
gameObject.layer = LayerMask.NameToLayer("Enemy");

组件操作

// 获取组件
GetComponent<T>()
GetComponentInChildren<T>()
GetComponentInParent<T>()
GetComponents<T>()

// 添加/移除
AddComponent<T>()
Destroy(GetComponent<T>())

// 启用/禁用
GetComponent<T>().enabled = true;

时间控制

Time.deltaTime              // 上一帧耗时
Time.fixedDeltaTime // FixedUpdate 间隔
Time.time // 游戏总时间
Time.timeScale // 时间缩放(0=暂停,1=正常,2=双倍)
Time.frameCount // 总帧数

// 延时
Invoke("MethodName", delay);
InvokeRepeating("Method", startDelay, repeatInterval);
CancelInvoke();

// 协程
StartCoroutine(MyCoroutine());
StopCoroutine(MyCoroutine());
StopAllCoroutines();

IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(2f);
yield return new WaitForEndOfFrame();
yield return new WaitForFixedUpdate();
yield return null; // 等待下一帧
}

数学工具

// Mathf
Mathf.Abs(x)
Mathf.Clamp(value, min, max)
Mathf.Clamp01(value)
Mathf.Lerp(a, b, t)
Mathf.LerpAngle(a, b, t)
Mathf.MoveTowards(current, target, maxDelta)
Mathf.SmoothDamp(current, target, ref velocity, smoothTime)
Mathf.Min(a, b)
Mathf.Max(a, b)
Mathf.Round(x)
Mathf.Floor(x)
Mathf.Ceil(x)
Mathf.Sqrt(x)
Mathf.Pow(x, y)
Mathf.Sin(angle)
Mathf.Cos(angle)
Mathf.Tan(angle)
Mathf.Asin(x)
Mathf.Acos(x)
Mathf.Atan2(y, x)
Mathf.Deg2Rad // 角度转弧度乘数
Mathf.Rad2Deg // 弧度转角度乘数
Mathf.PI
Mathf.Infinity

// 随机数
Random.value // 0.0 到 1.0
Random.Range(min, max) // 范围内随机
Random.insideUnitSphere // 单位球内随机点
Random.insideUnitCircle // 单位圆内随机点
Random.onUnitSphere // 单位球表面随机点
Random.ColorHSV() // 随机颜色

动画

Animator animator = GetComponent<Animator>();

// 设置参数
animator.SetFloat("Speed", 5f);
animator.SetInteger("Health", 100);
animator.SetBool("IsRunning", true);
animator.SetTrigger("Jump");

// 获取参数
float speed = animator.GetFloat("Speed");
bool isRunning = animator.GetBool("IsRunning");

// 播放动画
animator.Play("AnimationName");
animator.CrossFade("AnimationName", 0.25f);

UI 操作

// 查找 UI 元素
GameObject.Find("Canvas/Button");
GameObject.FindGameObjectWithTag("UI");

// 常用 UI 组件
Text text = GetComponent<Text>();
TextMeshProUGUI tmp = GetComponent<TextMeshProUGUI>();
Button button = GetComponent<Button>();
Slider slider = GetComponent<Slider>();
Image image = GetComponent<Image>();

// 按钮事件
button.onClick.AddListener(OnButtonClick);
button.onClick.RemoveListener(OnButtonClick);
button.onClick.RemoveAllListeners();

场景管理

using UnityEngine.SceneManagement;

// 加载场景
SceneManager.LoadScene("SceneName");
SceneManager.LoadScene(sceneIndex);
SceneManager.LoadScene("SceneName", LoadSceneMode.Additive);

// 异步加载
AsyncOperation op = SceneManager.LoadSceneAsync("SceneName");
op.allowSceneActivation = false; // 控制激活时机
op.progress; // 加载进度 0-0.9

// 获取场景
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
int sceneIndex = currentScene.buildIndex;

// 场景信息
SceneManager.GetSceneByName("SceneName");
SceneManager.GetSceneByBuildIndex(0);
SceneManager.sceneCount;
SceneManager.sceneCountInBuildSettings;

常用特性

// 序列化
[SerializeField]
private int privateField;

[HideInInspector]
public int hiddenField;

[Range(0, 100)]
public int rangedValue;

[Tooltip("说明文字")]
public int tooltipField;

[Header("分组标题")]
public int groupedField;

[Space(10)]
public int spacedField;

// 组件依赖
[RequireComponent(typeof(Rigidbody))]
public class MyClass : MonoBehaviour { }

// 执行顺序
[DefaultExecutionOrder(100)]
public class MyClass : MonoBehaviour { }

调试工具

// 日志
Debug.Log("普通信息");
Debug.LogWarning("警告信息");
Debug.LogError("错误信息");
Debug.LogFormat("数值: {0}", value);

// 绘制
Debug.DrawLine(start, end, Color.red, duration);
Debug.DrawRay(origin, direction, Color.green, duration);

// 断言
Debug.Assert(condition, "条件不满足");
Debug.Break(); // 暂停编辑器

资源路径

Application.dataPath          // Assets 文件夹路径
Application.persistentDataPath // 持久化数据路径
Application.temporaryCachePath // 临时缓存路径
Application.streamingAssetsPath // StreamingAssets 路径

平台判断

// 编译指令
#if UNITY_EDITOR
// 编辑器
#endif

#if UNITY_STANDALONE
// PC/Mac/Linux
#endif

#if UNITY_ANDROID
// Android
#endif

#if UNITY_IOS
// iOS
#endif

#if UNITY_WEBGL
// WebGL
#endif

// 运行时判断
Application.platform == RuntimePlatform.WindowsEditor;
Application.platform == RuntimePlatform.WindowsPlayer;
Application.platform == RuntimePlatform.Android;
Application.platform == RuntimePlatform.IPhonePlayer;

常用层索引

索引
Default0
TransparentFX1
Ignore Raycast2
Water4
UI5
// 层遮罩
LayerMask mask = LayerMask.GetMask("Enemy", "Obstacle");
LayerMask mask = 1 << LayerMask.NameToLayer("Enemy");