您的位置:首页 > 移动开发 > Unity3D

Unity自定义定时器

2015-06-03 18:00 579 查看
自己写的一个Timer,绑定到一个prefab上,使用时直接Instantaite,要用几个就Instantiate几个,非常方便

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour
{
private float _time;
private float _lastTime;
private bool _isStart;

public float time
{
get { return _time; }
}

public bool isStart
{
get { return _isStart; }
}

// Use this for initialization
void Start()
{
_time = 0;
_lastTime = 0;
_isStart = false;
}

// Update is called once per frame
void Update()
{
if (_isStart)
{
_time = Time.time - _lastTime;
//Debug.Log("Time:" + _time);
}
}

public void RestartTimer()
{
_lastTime = Time.time;
_isStart = true;
Debug.Log("RestartTimer");
}

public void StopTimer()
{
if (_isStart)
{
_lastTime = 0;
_time = 0;
_isStart = false;
Debug.Log("StopTimer");
}
}

public void PauseTimer()
{
if (_isStart)
{
_lastTime = _time;
_isStart = false;
Debug.Log("PauseTimer");
}
}

public void StartTimer()
{
if (!_isStart)
{
_lastTime = Time.time - time;
_isStart = true;
Debug.Log("StartTimer");
}
}

#region //for test
//void OnGUI()
//{
//    if (GUI.Button(new Rect(0, 0, 200, 200), "Start"))
//    {
//        StartTimer();
//    }
//    if (GUI.Button(new Rect(200, 0, 200, 200), "Pause"))
//    {
//        PauseTimer();
//    }
//    if (GUI.Button(new Rect(400, 0, 200, 200), "Stop"))
//    {
//        StopTimer();
//    }
//    if (GUI.Button(new Rect(600, 0, 200, 200), "Restart"))
//    {
//        RestartTimer();
//    }
//}
#endregion
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity 定时器