This question was
closed Dec 07, 2017 at 02:02 PM by
NEGATIVERAGDOLL for the following reason:
The question is answered, right answer was accepted
Question by
NEGATIVERAGDOLL · Dec 01, 2017 at 08:28 AM ·
c#scripting problemtogglecounter
How can I add a toggle to this FPS counter script?
Hello, I am using the standard fps counter script and I am wondering how I could ad a toggle to it. Basically so it's invisible unless you press a button on the keyboard. Thank you in advanced. Here's the script:
using System;
using UnityEngine;
using UnityEngine.UI;
namespace UnityStandardAssets.Utility
{
[RequireComponent(typeof (Text))]
public class FPSCounter : MonoBehaviour
{
const float fpsMeasurePeriod = 0.5f;
private int m_FpsAccumulator = 0;
private float m_FpsNextPeriod = 0;
private int m_CurrentFps;
const string display = "{0} FPS";
private Text m_Text;
private void Start()
{
m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod;
m_Text = GetComponent<Text>();
}
private void Update()
{
// measure average frames per second
m_FpsAccumulator++;
if (Time.realtimeSinceStartup > m_FpsNextPeriod)
{
m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod);
m_FpsAccumulator = 0;
m_FpsNextPeriod += fpsMeasurePeriod;
m_Text.text = string.Format(display, m_CurrentFps);
}
}
}
}
Comment
Best Answer
Answer by Hellium · Dec 01, 2017 at 09:17 AM
using System; using UnityEngine; using UnityEngine.UI;
namespace UnityStandardAssets.Utility
{
[RequireComponent(typeof (Text))]
public class FPSCounter : MonoBehaviour
{
public KeyCode toggleKey ;
const float fpsMeasurePeriod = 0.5f;
private int m_FpsAccumulator = 0;
private float m_FpsNextPeriod = 0;
private int m_CurrentFps;
const string display = "{0} FPS";
private Text m_Text;
private bool hidden ;
private void Start()
{
m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod;
m_Text = GetComponent<Text>();
}
private void Update()
{
if( Input.GetKeyUp( toggleKey ) )
Toggle() ;
if( hidden )
return ;
// measure average frames per second
m_FpsAccumulator++;
if (Time.realtimeSinceStartup > m_FpsNextPeriod)
{
m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod);
m_FpsAccumulator = 0;
m_FpsNextPeriod += fpsMeasurePeriod;
m_Text.text = string.Format(display, m_CurrentFps);
}
}
public void Show()
{
hidden = false;
m_Text.gameObject.SetActive(true) ;
}
public void Hide()
{
hidden = true ;
m_Text.gameObject.SetActive(false) ;
}
public void Toggle()
{
if(hidden)
Show() ;
else
Hide() ;
}
}
}