本文主要是介绍Xlua 热更新 实现显示帧率,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
第一步:导入Xlua插件
链接: 项目目录预览 - xLua - GitCode
进入链接,下载zip,进入Asset文件,将其中所有目录导入Unity的Asset中。
第二步:创建脚本 XLuaFPSDisplay.cs
复制粘贴以下代码,然后将脚本挂载到任意对象。
using XLua;
using UnityEngine;public class XLuaFPSDisplay : MonoBehaviour
{LuaEnv luaEnv;void Start(){luaEnv = new LuaEnv();luaEnv.DoString("require('FPSDisplay').Start()");}void Update(){luaEnv.DoString("require('FPSDisplay').Update()");}void OnDestroy(){luaEnv.Dispose();}
}
第三步:在sublime Text或者vs中创建lua脚本 FPSDisplay.lua
复制粘贴以下代码:
local UnityEngine = CS.UnityEngine
print(UnityEngine);
local FPSDisplay = {}print("成功加载了FPSDisplay")-- 在Start函数中初始化计时器和帧数变量
function FPSDisplay.Start()FPSDisplay.deltaTime = 0.0FPSDisplay.updateRate = 4 -- 更新频率,每4帧更新一次FPSDisplay.frameCount = 0FPSDisplay.timePassed = 0.0-- 创建一个UI文本对象用来显示帧率local canvas = UnityEngine.GameObject.Find("Canvas");FPSDisplay.fpsTextObj = UnityEngine.GameObject("FPSText")FPSDisplay.fpsTextObj.transform:SetParent(canvas.transform)local rectTransform = FPSDisplay.fpsTextObj:AddComponent(typeof(UnityEngine.RectTransform))rectTransform.anchorMin = UnityEngine.Vector2.zerorectTransform.anchorMax = UnityEngine.Vector2.onerectTransform.sizeDelta = UnityEngine.Vector2.zerorectTransform.anchoredPosition3D = UnityEngine.Vector3.zerolocal textComponent = FPSDisplay.fpsTextObj:AddComponent(typeof(UnityEngine.UI.Text))
textComponent.fontSize = 78FPSDisplay.fpsTextObj:GetComponent(typeof(UnityEngine.UI.Text)).font = UnityEngine.Resources.GetBuiltinResource(typeof(UnityEngine.Font), "Arial.ttf")
end-- 在Update函数中更新帧率计数和显示
function FPSDisplay.Update()FPSDisplay.frameCount = FPSDisplay.frameCount + 1FPSDisplay.deltaTime = FPSDisplay.deltaTime + UnityEngine.Time.unscaledDeltaTimeif FPSDisplay.frameCount % FPSDisplay.updateRate == 0 thenlocal fps = FPSDisplay.updateRate / FPSDisplay.deltaTimelocal textComponent = FPSDisplay.fpsTextObj:GetComponent(typeof(UnityEngine.UI.Text))textComponent.text = string.format("FPS: %.2f", fps)FPSDisplay.deltaTime = 0.0end
end
print("代码结束")
return FPSDisplay
第四步:运行即可
这篇关于Xlua 热更新 实现显示帧率的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!