Skip to content

Instantly share code, notes, and snippets.

@eXponenta
Forked from alerdenisov/Analyser.cs
Last active August 30, 2017 11:54
Show Gist options
  • Save eXponenta/2f6903984fc460bdc59d5d27188d8546 to your computer and use it in GitHub Desktop.
Save eXponenta/2f6903984fc460bdc59d5d27188d8546 to your computer and use it in GitHub Desktop.
FPS UI Graph
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace FpsAnalyzer
{
[ExecuteInEditMode]
public class Analyser : MaskableGraphic
{
[SerializeField] private int frames = 50;
[SerializeField] private bool useGradient;
[SerializeField] private Gradient fpsMap;
[Range(1, 20)]
[SerializeField] private int UpdatePerFrame = 10;
private List<UIVertex> vertices = new List<UIVertex>();
private float deltaTime;
private int frame;
void Update()
{
//Calculate FPS
deltaTime += (Time.deltaTime - deltaTime) / Mathf.Max(10, UpdatePerFrame);
float msec = deltaTime * 1000.0f;
float cfps = 1.0f / deltaTime;
if (frame % UpdatePerFrame == 0)
{
var lfps = 0f;
if (vertices.Count > 0)
{
lfps = vertices[vertices.Count - 1].position.y;
}
var ccolor = CalculateColor(cfps);
var lcolor = CalculateColor(lfps);
vertices.Add(CreateVertex(ccolor, frame - 0, cfps));
vertices.Add(CreateVertex(ccolor, frame - 0, 0));
vertices.Add(CreateVertex(lcolor, frame - UpdatePerFrame, 0));
vertices.Add(CreateVertex(lcolor, frame - UpdatePerFrame, 0));
vertices.Add(CreateVertex(lcolor, frame - UpdatePerFrame, lfps));
vertices.Add(CreateVertex(ccolor, frame - 0, cfps));
if (vertices.Count > frames * 6)
{
vertices.RemoveRange(0, vertices.Count - frames * 6);
}
(transform as RectTransform).anchoredPosition = Vector3.left * (frame - vertices.Count / 6);
SetAllDirty();
}
frame++;
}
private Color CalculateColor(float fps)
{
if (useGradient)
{
return fpsMap.Evaluate(Mathf.Clamp01(fps / 60f));
}
return Color.Lerp(Color.red, Color.green, Mathf.Clamp01(fps / 60f));
}
private UIVertex CreateVertex(Color clr, int frame, float height)
{
var vert = UIVertex.simpleVert;
vert.position = new Vector3(frame, height);
vert.color = clr;
return vert;
}
/// <summary>
/// Create mesh of graph
/// </summary>
/// <param name="vh"></param>
protected override void OnPopulateMesh(VertexHelper vh)
{
base.OnPopulateMesh(vh);
vh.Clear();
vh.AddUIVertexTriangleStream(vertices);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment