如何查看unity文档和API手册?
打开unity,找到help,下面有两个模块—— Unity Manual和Scripting Reference,就是unity文档和API手册,打开即可查看。
如果没有的话,则需要在官网上重新下载一下,然后在安装的时候勾选一下就可以了。
Unity中的事件方法
(Start方法和Update方法均为事件方法)
在打开的脚本中默认继承MonoBehaviour(F12打开),MonoBehaviour继承Behaviour,Behaviour继承Component,Component继承Object
-
Start只执行一次,Update执行多次
-
Reset:在Editor模式下触发,在编辑器中,当脚本被附加(attached)和reset的时候会触发(测试出现失误)
-
Awake、OnEnable、Start:当场景开始运行或者对象物体实例化的时候开始调用
-
FixedUpdate:每秒固定调用次数,一般为每秒60帧,每帧调用的次数不一定是一次
Update、LateUpdate:每帧调用一次,和运行环境有关 -
OnTrigger、OnCollision:用来触发触发器和碰撞器
-
OnMouse:Input Event(输入事件),跟鼠标操作有关的一些事件
-
OnDrawGizmos:场景中对象物体的辅助线,只能在Scene模式下显示
测试代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class API01EventFunction : MonoBehaviour {
void Awake()
{
Debug.Log("Awake");
}
void OnEnable()
{
Debug.Log("OnEnable");
}
void Start () {
Debug.Log("Start");
}
void FixedUpdate()
{
Debug.Log("FixedUpdate");
}
void Update () {
Debug.Log("Update");
}
void LateUpdate()
{
Debug.Log("LateUpdate");
}
void OnApplicationPause()
{
Debug.Log("OnApplicationPause");
}
void OnDisable()
{
Debug.Log("OnDisable");
}
void OnApplicationQuit()
{
Debug.Log("OnApplicationQuit");
}
void Reset()
{
Debug.Log("Reset");
}
void OnDestroy()
{
Debug.Log("OnDestroy");
}
}
Time类
- Time.captureFramerate:通过设置帧的速率,实现屏幕截图,让屏幕截图可以在当前帧完成
- Time.deltaTime:代表当前帧所占用的时间(大概为1/60s左右),跟实际的运行环境、硬件、游戏逻辑有关,相对于SmoothDeltaTime来说变化比较大
- Time.fixedDeltaTime:代表当前帧所占用的固定时间
帧数设置:Edit–Project Settings–Time - FixedTime、realtimeSinceStartup、time:代表从游戏开始到现在所运行的时间
FixedTime、Time:当游戏跳转到下一个场景的时候,时间还会一直增长,(以游戏的开始和结束为单位)
realtimeSinceStartup:当游戏暂停或者后台运行的时候,时间还会一直增加 - frameCount:代表帧数——从游戏开始到现在一共运行的帧数
- timeScale:时间比例,实现游戏暂停或者加速播放,默认等于一
- SmoothDeltaTime:以平滑的时间间隔变化
- timeSinceLevelLoad:从当前场景加载完成之后,游戏所运行的时间;当游戏跳转到下一个场景的时候,时间开始重新计算(以场景为单位)
- unscaledTime:游戏从开始到现在所运行的时间,不受Time.timeScale的影响
Time.deltaTime和realtimeSinceStartup的使用
- Time.deltaTime:时间间隔,用来控制与动画、运动有关的事件,表示每帧所占用的时间(Time.deltaTime受Time.timeScale影响)
- realtimeSinceStartup:做性能测试
例:加法运算与乘法运算性能测试
测试代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class API02Time : MonoBehaviour {
public Transform cube;
public int runCount = 10000;
void Start() {
float time00 = Time.realtimeSinceStartup;
for (int i = 0; i < runCount; i++)
{
Method0();
}
float time0 = Time.realtimeSinceStartup;
Debug.Log(time0 - time00);
float time1 = Time.realtimeSinceStartup;
for (int i = 0; i < runCount; i++)
{
Method1();
}
float time2 = Time.realtimeSinceStartup;
Debug.Log(time2 - time1);//Method1执行10000次所用的时间
float time3 = Time.realtimeSinceStartup;
for (int i = 0; i < runCount; i++)
{
Method2();
}
float time4 = Time.realtimeSinceStartup;
Debug.Log(time4 - time3);//Method2执行10000次所用的时间
}
void Method0()
{
}//作对照
void Method1()
{
int i = 2;
i += 2;
i += 2;
}
void Method2()
{
int i = 2;
i *= 2;
i *= 2;
}
}
一般来说,调用空方法的性能最小,乘法要比加法性能大,如果出现错误,可能是运算太简单,测试不出来。