- 尽量避免每帧处理
比如:
1
function Update() { DoSomeThing(); }
可改为每5帧处理一次:
1
function Update() { if(Time.frameCount % 5 == 0) { DoSomeThing(); } }
2. 定时重复处理用 InvokeRepeating 函数实现
比如,启动0.5秒后每隔1秒执行一次 DoSomeThing 函数:
1
function Start() { InvokeRepeating(“DoSomeThing”, 0.5, 1.0); }
3. 优化 Update, FixedUpdate, LateUpdate 等每帧处理的函数
函数里面的变量尽量在头部声明。
比如:
1
function Update() { var pos: Vector3 = transform.position; }
可改为
1
private var pos: Vector3; function Update(){ pos = transform.position; }
4. 主动回收垃圾
给某个 GameObject 绑上以下的代码:
1
function Update() { if(Time.frameCount % 50 == 0) { System.GC.Collect(); } }
5. 运行时尽量减少 Tris 和 Draw Calls
预览的时候,可点开 Stats,查看图形渲染的开销情况。特别注意 Tris 和 Draw Calls 这两个参数。