Unity计时器脚本

目的:测试自己写的函数或整个工程的用时

自定义计时器类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Timer : MonoBehaviour
{
    
    
    public bool isStart;
    public float CurrentTime = 0.0f;
    public float PastTime = 0.0f;
    public float DurTime = 0.0f;
    public static Timer CreateTimer(string gobjName = "Timer")
    {
    
    
        GameObject g = new GameObject(gobjName);
        Timer timer = g.AddComponent<Timer>();

        return timer;
    }

    public void StartProcess()
    {
    
    
        isStart = true;
    }

    public float StopProcess()
    {
    
    
        DurTime = CurrentTime - PastTime;
        PastTime = CurrentTime;
        return DurTime;
    }

    // Start is called before the first frame update
    void Start()
    {
    
    
        
    }

    // Update is called once per frame
    void Update()
    {
    
    
        if(isStart)
        {
    
    
            CurrentTime += Time.deltaTime;     
        }

    }

}

调用计时器函数

public class Main : MonoBehaviour
{
    
    
    public Timer Mytimer;//记住,不要在这里CreateTimer。Unity的底层设计应该是在start()前是无法检索到其他脚本的。
    void Start()
    {
    
    
    	Mytimer = Timer.CreateTimer();
    }
    void Update()
    {
    
    
		Mytimer.StartProcess();
		//YourTestFunctions
		 Debug.Log(Mytimer.StopProcess().ToString("f4"));
	}
}

其中,.ToString("f4")是为了保留4位小数

Reference

https://blog.51cto.com/u_15296123/5307152

猜你喜欢

转载自blog.csdn.net/qq_41598072/article/details/126604001
今日推荐