I want to expose bonus variable in the inspector. This is my code:
public float bonus // in percent [0,1]
{
get { return bonus; }
set
{
if (value < 0f && value > 1f)
{
Debug.Log("bonus should be [0,1], clamping...");
}
bonus = Mathf.Clamp01(value);
}
}
Is there a way to achieve this without doing Custom Inspector code? I also tried putting [SerializeField] on top of it but it didn’t work.
You could use custom editor, i needed to serialize a getter/setter as well, this here is an example of accessing data outside of the class scope to a different component ( text color ) and an local variable ( aim position ). This potentially allows serialization of virtually anything you want ( assuming your getter and setter won’t cause infinite recursion )
// Scripts folder
public class MyObject : MonoBehaviour
{
// ...
[SerializeField] Color s_color; public Color color
{
get
{
return GetComponent<Text>().color;
}
set
{
GetComponent<Text>().color = value;
this.s_color = value;
}
}
[SerializeField] Vector2 s_aim; public Vector2 aim
{
get
{
return s_aim;
}
set
{
this.s_aim = value;
}
}
public void Serialize()
{
color = s_color;
aim = s_aim;
}
}
// Editor folder
[CustomEditor( typeof( MyObject ) )]
[CanEditMultipleObjects]
public class MyObjectEditor : Editor
{
SerializedProperty s_color;
SerializedProperty s_aim;
void FindProperties()
{
s_color = serializedObject.FindProperty("s_color");
s_aim = serializedObject.FindProperty("s_aim");
}
void DrawGUI()
{
EditorGUILayout.PropertyField( s_color, new GUIContent("Color") );
EditorGUILayout.PropertyField( s_aim, new GUIContent("Aim") );
}
void OnEnable()
{
CastTargets();
FindProperties();
}
MyObject m_target;
List<MyObject> m_targets;
void CastTargets()
{
m_target = ( MyObject ) target;
m_targets = new List<MyObject>();
foreach (var t in targets)
{
MyObject obj = ( MyObject ) t;
m_targets.Add( obj );
obj.Initialize();
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawGUI();
serializedObject.ApplyModifiedProperties();
m_targets.ForEach( obj => obj.Serialize() );
}
}
Edit: just read @sarahnorthway source code, looks like this one is easier to use +1