Created
September 13, 2018 11:36
-
-
Save noisecrime/1e9eeff9f9e1d8df8fe18010d9625c3a to your computer and use it in GitHub Desktop.
Example of how to expose a field from a class reference and have it update the inspector at an 'appropriate' framerate
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 UnityEngine; | |
public class UpdateInspectorBehaviour : MonoBehaviour | |
{ | |
public class CustomValueClass | |
{ | |
public int _MyUpdatingValue; | |
} | |
public CustomValueClass _CustomValueClass; | |
private void OnEnable () | |
{ | |
_CustomValueClass = new CustomValueClass(); | |
} | |
private void OnDisable () | |
{ | |
_CustomValueClass = null; | |
} | |
void Update () | |
{ | |
_CustomValueClass._MyUpdatingValue++; | |
} | |
} |
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 UnityEditor; | |
/// <summary> | |
/// Example of how to expose a field from a class reference and have it update the inspector at an 'appropriate' framerate. | |
/// In practice though its easier to create a duplicate field in the monoBehaviour, update its value and let Unity deal with it. | |
/// However this is still useful code to know. | |
/// </summary> | |
[CustomEditor(typeof(UpdateInspectorBehaviour))] | |
public class UpdateInspectorBehaviourEditor : Editor | |
{ | |
private int thisSample = 0; | |
private int lastSample = int.MaxValue; | |
bool UpdatePerFrameInfo () | |
{ | |
lastSample = thisSample; | |
UpdateInspectorBehaviour myTarget = (UpdateInspectorBehaviour) target; | |
thisSample = (null != myTarget._CustomValueClass ? myTarget._CustomValueClass._MyUpdatingValue : 0); | |
// Returns if we need a repaint | |
return EditorApplication.isPlaying && thisSample != lastSample; | |
} | |
// If return is true will refresh Inspector once per frame. Best method as avoids editor overhead getting too large. | |
public override bool RequiresConstantRepaint () | |
{ | |
bool requiresRepaint = UpdatePerFrameInfo(); | |
return requiresRepaint; | |
} | |
public override void OnInspectorGUI() | |
{ | |
EditorGUILayout.LabelField("MyUpdatingValue", thisSample.ToString("D6")); | |
EditorGUILayout.Space(); | |
DrawDefaultInspector(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment