基础知识体系架构介绍
1. 核心组件系统 GameObject 和 Component
// GameObject 是场景中所有实体的基类
GameObject obj = new GameObject("MyObject");
// 添加组件
obj.AddComponent<Rigidbody>();
obj.AddComponent<BoxCollider>();
// 获取组件
var rb = obj.GetComponent<Rigidbody>();
var controller = obj.GetComponent<MaterialBreathingLightController>();
// 在子对象中查找
var tweenablePart = obj.GetComponentInChildren<TweenableTransformController>();
// 在父对象中查找
var parent = obj.GetComponentInParent<ParentController>();
// 获取所有组件
var allComponents = obj.GetComponents<Component>();
2. Transform 层级系统
// 位置、旋转、缩放
transform.position = new Vector3(0, 10, 0);
transform.rotation = Quaternion.Euler(0, 90, 0);
transform.localScale = new Vector3(2, 2, 2);
// 本地坐标 vs 世界坐标
transform.localPosition; // 相对父对象
transform.position; // 世界坐标
// 层级操作
transform.parent = parentTransform;
transform.SetParent(newParent);
var child = transform.GetChild(0);
int childCount = transform.childCount;
// 查找子对象
Transform found = transform.Find("ChildName");
Transform deep = transform.Find("Child/GrandChild");
3. 生命周期函数
public class MyScript : MonoBehaviour {
// 初始化(只执行一次,在第一帧之前)
void Awake() { }
// 启用时执行
void OnEnable() { }
// 第一帧之前(在Awake之后)
void Start() { }
// 每帧更新
void Update() { }
// 固定时间间隔更新(物理)
void FixedUpdate() { }
// 在Update之后执行(常用于相机跟随)
void LateUpdate() { }
// 禁用时执行
void OnDisable() { }
// 销毁时执行
void OnDestroy() { }
}
执行顺序:
Awake → OnEnable → Start → FixedUpdate → Update → LateUpdate → OnDisable → OnDestroy
4. 协程 (Coroutine)
// 启动协程
StartCoroutine(MyCoroutine());
StartCoroutine(DelayedAction(2.0f));
// 停止协程
StopCoroutine(myCoroutine);
StopAllCoroutines();
// 协程定义
IEnumerator MyCoroutine() {
Debug.Log("开始");
yield return new WaitForSeconds(2f); // 等待2秒
Debug.Log("2秒后");
yield return new WaitForFixedUpdate(); // 等待下一个物理帧
yield return null; // 等待下一帧
yield return new WaitUntil(() => isReady); // 等待条件满足
Debug.Log("结束");
}
IEnumerator DelayedAction(float delay) {
yield return new WaitForSeconds(delay);
DoSomething();
}
5. 预制体 (Prefab) 与实例化
// 实例化预制体
GameObject instance = Instantiate(prefab);
GameObject instance2 = Instantiate(prefab, position, rotation);
GameObject instance3 = Instantiate(prefab, parent);
// 销毁对象
Destroy(gameObject);
Destroy(gameObject, 2f); // 2秒后销毁
// 立即销毁(慎用)
DestroyImmediate(gameObject);
// 场景切换时不销毁
DontDestroyOnLoad(gameObject);
6. 碰撞与触发器
// 碰撞检测(需要Collider和Rigidbody)
void OnCollisionEnter(Collision collision) {
Debug.Log("碰撞开始: " + collision.gameObject.name);
}
void OnCollisionStay(Collision collision) {
Debug.Log("持续碰撞");
}
void OnCollisionExit(Collision collision) {
Debug.Log("碰撞结束");
}
// 触发器检测(Collider设置为IsTrigger)
void OnTriggerEnter(Collider other) {
if (other.CompareTag("Player")) {
Debug.Log("玩家进入触发区域");
}
}
void OnTriggerStay(Collider other) { }
void OnTriggerExit(Collider other) { }
7. 输入系统 旧输入系统
void Update() {
// 键盘输入
if (Input.GetKeyDown(KeyCode.Space)) {
Debug.Log("空格键按下");
}
// 鼠标输入
if (Input.GetMouseButtonDown(0)) { // 左键
Debug.Log("鼠标左键点击");
}
// 轴输入(-1到1)
float horizontal = Input.GetAxis("Horizontal"); // A/D 或 左/右箭头
float vertical = Input.GetAxis("Vertical"); // W/S 或 上/下箭头
// 鼠标位置
Vector3 mousePos = Input.mousePosition;
}
8. 向量运算 (Vector3)
// 创建向量
Vector3 v1 = new Vector3(1, 2, 3);
Vector3 v2 = Vector3.zero; // (0, 0, 0)
Vector3 v3 = Vector3.one; // (1, 1, 1)
Vector3 v4 = Vector3.up; // (0, 1, 0)
Vector3 v5 = Vector3.forward; // (0, 0, 1)
// 向量运算
Vector3 sum = v1 + v2;
Vector3 diff = v1 - v2;
Vector3 scaled = v1 * 2;
// 距离
float distance = Vector3.Distance(v1, v2);
// 插值(平滑移动)
Vector3 result = Vector3.Lerp(start, end, 0.5f); // 中点
Vector3 smooth = Vector3.Slerp(start, end, t); // 球形插值
// 方向
Vector3 direction = (target - current).normalized;
// 点积(判断朝向)
float dot = Vector3.Dot(v1, v2);
// 叉积(计算垂直向量)
Vector3 cross = Vector3.Cross(v1, v2);
9. 四元数旋转 (Quaternion)
// 创建旋转
Quaternion rot1 = Quaternion.Euler(0, 90, 0); // 欧拉角
Quaternion rot2 = Quaternion.identity; // 无旋转
// 看向目标
transform.rotation = Quaternion.LookRotation(direction);
// 平滑旋转
transform.rotation = Quaternion.Lerp(current, target, Time.deltaTime * speed);
transform.rotation = Quaternion.Slerp(current, target, t);
// 旋转向量
Vector3 rotated = rotation * vector;
10. Time 时间管理
void Update() {
// 帧间隔时间(秒)
float deltaTime = Time.deltaTime;
// 游戏开始后的时间
float time = Time.time;
// 不受时间缩放影响的时间
float realTime = Time.unscaledTime;
float unscaledDelta = Time.unscaledDeltaTime;
// 时间缩放(慢动作/加速)
Time.timeScale = 0.5f; // 半速
Time.timeScale = 0f; // 暂停
Time.timeScale = 2f; // 2倍速
// 固定帧率间隔
float fixedDelta = Time.fixedDeltaTime; // 默认0.02秒(50fps)
}
11. 场景管理
using UnityEngine.SceneManagement;
// 加载场景
SceneManager.LoadScene("SceneName");
SceneManager.LoadScene(1); // 按索引
// 异步加载
StartCoroutine(LoadSceneAsync("SceneName"));
IEnumerator LoadSceneAsync(string sceneName) {
AsyncOperation op = SceneManager.LoadSceneAsync(sceneName);
while (!op.isDone) {
float progress = op.progress; // 加载进度
yield return null;
}
}
// 获取当前场景
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
12. 资源加载
// 从Resources文件夹加载
GameObject prefab = Resources.Load<GameObject>("Prefabs/MyPrefab");
Sprite sprite = Resources.Load<Sprite>("Sprites/Icon");
// 异步加载
ResourceRequest request = Resources.LoadAsync<GameObject>("Prefabs/MyPrefab");
yield return request;
GameObject loaded = request.asset as GameObject;
13. 标签和层级
// 标签
gameObject.tag = "Player";
if (gameObject.CompareTag("Enemy")) {
Debug.Log("这是敌人");
}
GameObject player = GameObject.FindGameObjectWithTag("Player");
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
// 层级(Layer)
gameObject.layer = LayerMask.NameToLayer("UI");
// 射线检测时使用层级遮罩
int layerMask = LayerMask.GetMask("Default", "Player");
14. 射线检测 (Raycast)
// 基础射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100f)) {
Debug.Log("击中: " + hit.collider.gameObject.name);
Vector3 hitPoint = hit.point;
GameObject hitObject = hit.collider.gameObject;
}
// 指定层级
int layerMask = LayerMask.GetMask("Ground");
if (Physics.Raycast(origin, direction, out hit, maxDistance, layerMask)) {
// 只检测Ground层
}
// 检测所有
RaycastHit[] hits = Physics.RaycastAll(ray, 100f);
15. 动画系统
// Animator控制
Animator animator = GetComponent<Animator>();
// 触发动画
animator.SetTrigger("Jump");
animator.SetBool("IsRunning", true);
animator.SetFloat("Speed", 5.0f);
animator.SetInteger("State", 1);
// 播放动画
animator.Play("Idle");
// 获取状态
AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0);
bool isPlaying = info.IsName("Run");
16. UI系统 (UGUI)
using UnityEngine.UI;
// Text
Text text = GetComponent<Text>();
text.text = "Hello World";
// Button
Button button = GetComponent<Button>();
button.onClick.AddListener(OnButtonClick);
void OnButtonClick() {
Debug.Log("按钮被点击");
}
// Image
Image image = GetComponent<Image>();
image.sprite = newSprite;
image.color = Color.red;
// Canvas Group(控制UI显示)
CanvasGroup canvasGroup = GetComponent<CanvasGroup>();
canvasGroup.alpha = 0.5f; // 透明度
canvasGroup.interactable = false; // 禁用交互
canvasGroup.blocksRaycasts = false; // 不阻挡射线
知识体系总结
Unity基础架构
├─ GameObject/Component 系统 ☆☆☆☆☆
├─ Transform 层级 ☆☆☆☆☆
├─ 生命周期 ☆☆☆☆☆
├─ 协程 ☆☆☆☆
├─ 预制体/实例化 ☆☆☆☆☆
├─ 碰撞/触发器 ☆☆☆☆
├─ 输入系统 ☆☆☆☆
├─ 向量/四元数 ☆☆☆☆
├─ 时间管理 ☆☆☆☆
├─ 场景管理 ☆☆☆
├─ 资源加载 ☆☆☆
├─ 标签和层级 ☆☆☆
├─ 射线检测 ☆☆☆
├─ 动画系统 ☆☆☆
└─ UI系统 ☆☆☆☆☆
Unity核心基础概念详解
2063

被折叠的 条评论
为什么被折叠?



