I’ve played a little bit last month writing editor’s extensions and custom inspectors.
I know Unity can’t serialize C# properties (I think because they have side effects). Despite that, I often need to access them through property accessors methods or getter/setters. I came up to always writing specific Editor classes for custom inspector code:
public class AClass : MonoBehaviour
{
[HideInInspector]
[SerializeField]
private string property;
public string Property
{
get{return _assetPath;}
set{
//other stuffs/side effects
_assetPath = value;
}}
/////////////////////
[CustomEditor (typeof(AClass ))]
public class AClass Editor : Editor
{
private AClass istance;
private SerializedProperty nodePath;
public void OnEnable()
{
istance = target as AClass;
}
public override void OnInspectorGUI()
{
Undo.SetSnapshotTarget(istance, "UndoAClass");
EditorGUI.BeginChangeCheck();
string val = EditorGUILayout.TextField("Value", istance.Property);
if (EditorGUI.EndChangeCheck())
{
Undo.CreateSnapshot();
Undo.RegisterSnapshot();
istance.Property = val;
}
}
Now, the above approach is a bit tedious since I have to write code like that for all classes field, but I haven’t find nothing better. My first question: is there anyway to improve the code above if I need to write a custom inspector code that need to modify a class field through C# property setter?
Some of my extension are becoming quite useful, at least for artist team that is working with them. I’m thinking about plublishing something on the AssetStore. When reading the guidelines I found the following sentences:
It’s a bit tedious handling all undos by hand like shown above, but it works. I should be compliant with that.
I’m not using Serialized Property. Here’s the second question: how can I use SerializedProperty if I need to modify serialized fields of my class through getter/setter?
I can’t do the following because I can’t handle side effects:
EditorGUILayout.PropertyField (instance.property, new GUIContent ("Property"));
Last question: If I can’t use SerializedProperty how can I manually support prefab ovverrides? Any example?
If anyone has additional suggestions on how improve my approach is really welcome
thanks in advance