Appearance
Unity基础
Object、Behaviour、MonoBehaviour、Component 之间的关系
Object
Unity 引擎中所有可序列化对象的基类,提供Instantiate、Destroy等最基础的生命周期管理,但不具备“挂载到 GameObject”的能力。Component
继承自Object,是所有“可挂载到 GameObject 上的功能模块”的基类。
每个 Component 实例必须依附于某个 GameObject,通过gameObject/transform属性访问其宿主。Behaviour
继承自Component,增加了“启用/禁用”概念,即enabled字段。
只要enabled == false,Update、OnGUI等帧回调便不会执行。
典型子类:MonoBehaviour、UIBehaviour。MonoBehaviour
继承自Behaviour,是绝大多数脚本逻辑的起点。
具备完整的脚本生命周期(Awake、Start、Update、OnDestroy…),并且只能在主线程中访问 Unity API。
因此:- 新建线程里无法直接
new MonoBehaviour()或调用GameObject.AddComponent<T>()。 - 若要在子线程中更新数据,需把结果封送(marshal)回主线程,再通过委托或
UnityMainThreadDispatcher应用到组件。
- 新建线程里无法直接
一句话总结:
Object → Component → Behaviour → MonoBehaviour,从左到右功能逐层叠加,最终得到的 MonoBehaviour 才是我们日常挂在 GameObject 上、能在主线程里调用 Unity API 的脚本组件。
常用API
Debug
Debug类用于调试,其结果是在Console中打印出相关信息。
Debug是脱离 MonoBehaviour 类的,因此可以在任何地方调用。Print需要在MonoBehaviour类中调用。
| 方法 | 详解 |
|---|---|
| Log | 控制台面板中输出一条消息 |
| LogWarning | 控制台面板中输出一条警告消息 |
| LogError | 控制台面板中输出一条错误消息 |
| DrawLine | 在指定的起始点和终点之间绘制一条直线 |
| DrawRay | 在指定的起始点向一个向量绘制一条直线 |
Time 时间类
| 属性方法 | 详解 |
|---|---|
| deltaTime | 上一帧到这一帧所花的时间 |
| fixedDeltaTime | 固定间隔时间 |
| time | 游戏开始到现在所花的总时间 |
| timeScale | 时间缩放值,默认为1.0 |
Mathf 数学类
| 属性方法 | 详解 |
|---|---|
| Deg2Rad | 角度转弧度 |
| Rad2Deg | 弧度转角度 |
| PI | 圆周率 |
| Abs | 绝对值 |
| Sin/Cos/Tan | 正弦/余弦/正切 |
| Asin/Acos/Atan | 反正弦/反余弦/反正切 |
| Clamp | 将数字限制在一个范围 |
| Clamp01 | 将数字限制在0~1 |
| Lerp | 线性插值 |
| Max | 返回最大值 |
| Min | 返回最小值 |
| Sqrt | 返回平方根 |
Application 应用类
该类主要与程序进行交互
| 属性方法 | 详解 |
|---|---|
| dataPath | 游戏数据文件夹路径 |
| persistentDataPath | 持久化游戏数据文件夹路径 |
| streamingAssetsPath | StreamingAssets文件夹路径 |
| temporaryCachePath | 临时文件夹路径 |
| runInBackground | 控制在后台时是否运行 |
| OpenURL | 打开一个URL |
| Quit | 退出 |
多线程
csharp
using System.Threading;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
// 创建多线程
ThreadStart ts = new ThreadStart(threadTest);
Thread thread = new Thread(ts);
// 开始多线程
thread.Start();
}
void threadTest()
{
// 该方法中的代码均在子线程中调用
Debug.Log("线程中");
// 线程休眠
Thread.Sleep(5000);
Debug.Log("5s过去了");
}
}csharp
using System.Threading;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
Debug.Log("忙活");
Debug.Log("忙活");
Debug.Log("忙活");
// 开始多线程
ThreadStart ts = new ThreadStart(MTest);
Thread thread = new Thread(ts);
thread.Start();
Debug.Log("继续忙活");
Debug.Log("继续忙活");
Debug.Log("继续忙活");
}
void MTest()
{
Debug.Log("开始烧水");
Thread.Sleep(5000);
Debug.Log("结束烧水");
}
}协程的使用
使用协程的类必须继承自MonoBehaviour
csharp
using System.Collections;
using UnityEngine;
public class Test : MonoBehaviour
{
private void Start()
{
Debug.Log("忙活");
StartCoroutine(ITest());
Debug.Log("继续忙活");
}
IEnumerator ITest()
{
Debug.Log("干点别的");
yield return new WaitForSeconds(5);
Debug.Log("干完了");
}
}