using TMPro;
using UnityEngine;
using UnityEngine.UI;
///
/// This script calculate the current fps and show it to a text ui.
///
public class UiDisplayFps : MonoBehaviour
{
public string formattedString = "{value} FPS";
public TextMeshProUGUI txtFps;
//public TextMeshProUGUI txtAlert;
public Image FPSc;
float _updateRatePerSeconds = 4.0F;
int _frameCount = 0;
float _dt = 0.0F;
float _maxFPS = float.NegativeInfinity;
[SerializeField] float _currentFPS = 0.0F;
float _minFPS = float.PositiveInfinity;
GameObject _testing; // testing??
TextMeshProUGUI _fpsStrengthText;
TextMeshProUGUI _memoryText;
TextMeshProUGUI _strengthText;
Image _bar;
private void Start()
{
//Application.runInBackground = true;
_testing = GameObject.Find("Testing");
GetFPSSTextRef();
GetTStrengthTextRef();
GetBarRef();
GetMemoryTextRef();
}
private void GetMemoryTextRef()
{
GameObject memoryGameObject = GameObject.Find("Memory");
if (memoryGameObject)
{
_memoryText = memoryGameObject.GetComponent();
}
}
private void GetBarRef()
{
GameObject BAR = GameObject.Find("BAR");
if (BAR)
{
_bar = BAR.GetComponent();
}
}
private void GetTStrengthTextRef()
{
GameObject T_StrengthGameObject = GameObject.Find("T_STRENGHT");
if (T_StrengthGameObject)
{
_strengthText = T_StrengthGameObject.GetComponent();
}
}
private void GetFPSSTextRef()
{
GameObject fpssGameObject = GameObject.Find("FPSS");
if (fpssGameObject)
{
_fpsStrengthText = fpssGameObject.GetComponent();
}
}
void Update()
{
UpdateFPS();
UpdateMemoryUsage();
}
private void UpdateUIElements()
{
txtFps.text = ConvertFPSToString();
FPSc.color = _currentFPS >= 45 ? Color.green : _currentFPS >= 25 ? Color.yellow : Color.red;
if (_testing)
{
_G.FPS = _currentFPS;
_fpsStrengthText.text = ConvertFPSToString();
_bar.color = _currentFPS >= 50 ? Color.green : _currentFPS >= 40 ? Color.yellow : Color.red;
_strengthText.text = _currentFPS >= 50 ? TRANS.This("T_GOOD") : _currentFPS >= 40 ? TRANS.This("T_MEDIUM") : TRANS.This("T_WEAK");
float S = _currentFPS / 60;
if (S > 1) S = 1;
float X = -180 + (360 * S) / 2;
_bar.transform.localScale = new Vector3(S, 1, 1);
_bar.transform.localPosition = new Vector3(X, 0, 1);
}
}
private void UpdateFPS()
{
_frameCount++;
_dt += Time.deltaTime;
//_dt += Time.unscaledDeltaTime;
if (_dt > 1.0 / _updateRatePerSeconds)
{
_currentFPS = _frameCount / _dt;
//_maxFPS = Mathf.Max(_maxFPS, _currentFPS);
//_minFPS = Mathf.Min(_minFPS, _currentFPS);
_frameCount = 0;
_dt -= 1.0F / _updateRatePerSeconds;
}
UpdateUIElements();
}
private string ConvertFPSToString()
{
return formattedString.Replace("{value}", System.Math.Round(_currentFPS, 1).ToString("0.0"));
}
private void UpdateMemoryUsage()
{
if (!_memoryText) { GetMemoryTextRef(); }
if (_memoryText)
{
_memoryText.text = "M:" + UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong() / 102400;
}
}
}