Created
November 15, 2010 12:53
-
-
Save zoon/700314 to your computer and use it in GitHub Desktop.
Unity3D Input: OnGUI vs.Update.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading; | |
using UnityEngine; | |
// [ExecuteInEditMode] | |
public class InputTest : MonoBehaviour | |
{ | |
private float _delay; | |
private float _fps; | |
private float _fpsTime; | |
private int _fpsFrames; | |
private int _clicksInGUI; | |
private int _clicksInUpdate; | |
private float _guiClicksToSec; | |
private float _clickInUpdateInSec; | |
private const int MaxDelay = 500; | |
void OnGUI() | |
{ | |
// every Event | |
var ec = Event.current; | |
if (ec.type == EventType.MouseDown && ec.button == 0) | |
++_clicksInGUI; // <---- | |
var w = Screen.width; | |
var h = Screen.height; | |
GUILayout.BeginArea(new Rect(w/4f, h/4f, w/2f, h/2f)); | |
{ | |
GUILayout.Label("FPS: " + _fps.ToString("f1")); | |
GUILayout.BeginHorizontal(); | |
{ | |
GUILayout.Label(string.Format("Delay: {0:0.#}", _delay)); | |
GUILayout.Label( | |
string.Format("Frame delay: [0,{0}] milliseconds", | |
MaxDelay)); | |
} | |
GUILayout.EndHorizontal(); | |
_delay = GUILayout.HorizontalSlider(_delay, 0, MaxDelay); | |
GUILayout.Label(string.Format("OnGUI clicks/sec: {0:0.#}", | |
_guiClicksToSec)); | |
GUILayout.Label(string.Format("Update clicks/sec: {0:0.#}", | |
_clickInUpdateInSec)); | |
} | |
GUILayout.EndArea(); | |
} | |
private void Update() | |
{ | |
// every frame | |
if (Input.GetMouseButtonDown(0)) | |
++_clicksInUpdate; // <---- | |
++_fpsFrames; | |
_fpsTime += Time.deltaTime; | |
if (_fpsTime >= 1f) | |
{ | |
_fps = _fpsFrames/_fpsTime; | |
_guiClicksToSec = _clicksInGUI/_fpsTime; | |
_clickInUpdateInSec = _clicksInUpdate/_fpsTime; | |
_fpsFrames = 0; | |
_fpsTime = 0; | |
_clicksInGUI = 0; | |
_clicksInUpdate = 0; | |
} | |
if (_delay >= 1f) | |
Thread.Sleep(Mathf.CeilToInt(_delay)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment