Common(十六)—— ShowFPS显示帧数

本文介绍了一个用于Unity游戏开发中实时显示FPS(每秒帧数)的脚本。该脚本通过挂载到GameObject上实现FPS及网络延迟的显示,并且能够自定义GUI样式以适应不同的UI需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录为:Assets/Scripts/Common/
ShowFPS.cs
这个脚本挂到一个GameObject上就可以了。

这里写图片描述

using UnityEngine;
using System.Collections;

public class ShowFPS: MonoBehaviour
{
    public static ShowFPS Instance
    {
        private set;
        get;
    }

    void OnEnable()
    {
        Instance = this;
    }

    void OnDisable()
    {
        Instance = null;
    }

    public float f_UpdateInterval = 0.5f;

    private float f_LastInterval;

    //总的渲染的帧数
    private int i_Frames = 0;
    private float f_Fps;

    //用这个可以改变默认GUI风格
    private GUIStyle style = new GUIStyle ();

    public float sSPing
    {
        get;
        set;
    }

    public float cSPing
    {
        get;
        set;
    }

    void Start()
    {
        //游戏会尽量以这个帧率运行
        Application.targetFrameRate = 300;
        f_LastInterval = Time.realtimeSinceStartup;
        i_Frames = 0;

        //设置GUI的风格
        style.fontSize = 10;
        style.normal.textColor = new Color (0, 255, 0, 255);
    }

    void OnGUI()
    {
        GUI.Label (new Rect (0, 0, 200, 200), "FPS:" + f_Fps.ToString ("f2"), style);
        GUI.Label (new Rect (0, 10, 200, 200), "sSPing:" + sSPing.ToString("f2"), style);
        GUI.Label (new Rect (0, 20, 200, 200), "cSPing:" + cSPing.ToString ("f2"), style);
    }

    void Update()
    {
        ++i_Frames;

        //f_UpdateInterval = 0.5f;
        //这里表示每隔0.5s计算一次帧数
        if (Time.realtimeSinceStartup > f_LastInterval + f_UpdateInterval)
        {
            //间隔时间内,渲染了多少帧,算出每秒帧数
            f_Fps = i_Frames / (Time.realtimeSinceStartup - f_LastInterval);

            i_Frames = 0;

            f_LastInterval = Time.realtimeSinceStartup;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值