Game Development Reference
In-Depth Information
if (!textComponent)
{
Debug.LogError
("This script needs to be attached to a Text component!");
enabled = false;
return;
}
}
Because we are using the
RequireComponent
attribute, we don't
actually have to have to put the error test for the component in the
script; however, it is a good practice to get into and will avoid nasty
bugs appearing, when you least expect it, when you reference other
components from scripts!
Lastly, we need an update loop to calculate the
FPS
and set the
Text
variable on the
Text
control:
void Update()
{
frameCount += 1;
timeLeft -= Time.deltaTime;
timePassed += Time.timeScale / Time.deltaTime;
//FPS Calculation each second
if (timeLeft <= 0f)
{
fps = timePassed / frameCount;
timeLeft = updateInterval;
timePassed = 0f;
frameCount = 0;
}
//Set the color of the text
if (fps < 30) { textComponent.color = Color.red; }
else if (fps < 60) { textComponent.color = Color.yellow; }
else { textComponent.color = Color.green; }
//Set Text string
textComponent.text = string.Format("{0}: FPS", fps);
}