1.代码
1.1用deltatime计时
public class TimeDemo : MonoBehaviour
{
private Text textTime;
public int second = 120;
public float totalTime;
int M ;
int S ;
private void Start()
{
textTime = this.GetComponent<Text>();
}
private void Update()
{
Timer2();
}
private void Timer2()
{
totalTime += Time.deltaTime;
if (totalTime >= 1)
{
second--;
if (second >= 0)
{
totalTime-=1;
M = second / 60;
S = second % 60;
textTime.text = string.Format("{0:d2}:{1:d2}", M, S);
if (M == 0 && S == 10)//剩十秒变红
textTime.color = Color.red;
}else Time.timeScale = 0;
}
}
}
1.2应用Invoke系列函数计时
public class TimeDemo : MonoBehaviour
{
private Text textTime;
public int second = 120;
int M ;
int S ;
private void Start()
{
textTime = this.GetComponent<Text>();
InvokeRepeating("Timer", 1, 1);
}
private void Timer()
{
second--;
M = second / 60;
S = second % 60;
textTime.text = string.Format("{0:d2}:{1:d2}", M, S);
if (M == 0 && S == 10)//剩十秒变红
textTime.color = Color.red;
if (second <= 0)
CancelInvoke("Timer");
}
}
2.出现NullReferenceException异常的原因
翻译为空引用异常,顾名思义就是进行了null.方法 的用法。
大部分情况为
1.无初始化
2.没挂文本文件
3.没有这个组件。
4.脚本没对应
3.使用Animation的异常发生
当录制animation动画前物品没有amimation组件,便会在录制时自动创建一个animater组件影响animation动画引用的正常使用。
正常情况下:
异常情况下: