- Home /
How to display computed getter in inspector?
I'm aware of the answers here on how to display public fields as read-only in the inspector, and I'm also aware of [SerializeField] to display private fields, which is the answer many gave for exposing getter/setter in the inspector.
However, I'd like to expose a read-only value in the inspector that is a getter of a computed value. So the value is not stored in any private fields. I do not wish to add any extra private fields to store the computed result, as there could be many of such getters and I don't wish to bloat it up.
For example:
public float a;
public float b;
// just an example. could be other formula
[HowToExposeInInspectorAsReadOnly?]
public float x { get { return a + 2 * b; } }
So when the values of a
and b
changes, you can also observe the read-only value of x
in the inspector, for debugging purposes.
Answer by pctroll · Jul 09, 2017 at 03:37 PM
I used a mixed approach.
First, I implemented the solution from @lev-lukomskyi http://answers.unity3d.com/questions/489942/how-to-make-a-readonly-property-in-inspector.html#
Then I used an approach from @mattrix to use the OnValidate event http://answers.unity3d.com/questions/413516/detect-when-a-property-is-changed-on-a-scriptableo.html#
[Range(1, 100)]
public int level;
[ReadOnly]
public float speed;
public float speedBase;
public float speedMultiplier;
private void Awake()
{
ComputeValues();
}
private void OnEnable()
{
ComputeValues();
}
private void OnValidate()
{
ComputeValues();
}
public void ComputeValues()
{
speed = (float)level * speedMultiplier * speedBase;
}
Answer by NoBrainer-David · Jul 09, 2017 at 05:30 PM
You could implement a custom inspector for that type, call the default inspector and then labels, showing the computed results. This should get you started.
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(MyType))]
public class MyTypeEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MyType myObject = (MyType ) target;
EditorGUILayout.LabelField("X x Y: ", myObject.x * myObject.y);
}
}
Your answer
Follow this Question
Related Questions
Is it possible to dynamically disable or validate properties in the inspector? 3 Answers
How to make public variable read-only during run-time? 3 Answers
Material doesn't have a color property '_Color' 4 Answers
Can I refer to a custom abstract class as a MonoBehaviour property? 1 Answer
Property values changed by custom editor are reset when start playing 2 Answers