OnInspectorGUI with prefabs

I have a class with a public integer field in a MonoBehaviour class which I want to set through the inspector, but I want to show a slider for setting the value in the inspector instead of a text field. I’m using the OnInspectorGUI() method to create a slider, and this works fine normally.

But, if I create a prefab for the object and try to set the value using the slider in the prefab, the value reverts back to what it was when I created the prefab. If I use the default text field to set the value, it works fine, as expected. Is there some way to get this to work with the slider in the prefab?

My Test Code:

[UnityEditor.CustomEditor (typeof (TestComponent))]
public class TestOnInspector : UnityEditor.Editor {
    public override void OnInspectorGUI () {
        TestComponent tc = (TestComponent) target;
        tc.testInt = UnityEditor.EditorGUILayout.IntSlider ("Test Int", tc.testInt, 0, 15);
        base.OnInspectorGUI();
    }
}

public class TestComponent : MonoBehaviour {
    public int testInt = 0;
}

I have two ways to do this:

First, Use Undo & SetDirty

[UnityEditor.CustomEditor(typeof(TestComponent))]
public class TestOnInspector : UnityEditor.Editor {
	public override void OnInspectorGUI() {
		TestComponent tc = (TestComponent)target;
		UnityEditor.Undo.RecordObject(tc, "Inspector");
		UnityEditor.EditorUtility.SetDirty(tc);
		tc.testInt = UnityEditor.EditorGUILayout.IntSlider("Test Int", tc.testInt, 0, 15);
		base.OnInspectorGUI();
	}
}

public class TestComponent : MonoBehaviour {
	public int testInt = 0;
}

Or, use SerializedProerty

[UnityEditor.CustomEditor(typeof(TestComponent))]
public class TestOnInspector : UnityEditor.Editor {
	public override void OnInspectorGUI() {
		SerializedProperty testIntProp = serializedObject.FindProperty("testInt");
		testIntProp.intValue = UnityEditor.EditorGUILayout.IntSlider("Test Int", testIntProp.intValue, 0, 15);
		serializedObject.ApplyModifiedProperties();
		base.OnInspectorGUI();
	}
}

public class TestComponent : MonoBehaviour {
	public int testInt = 0;
}

I don’t have a specific answer to what you want but if you don’t NEED a custom inspector, you could solve your problem by using

[Range(0,15]
public int testInt = 0;

directly in your base class script. This should solve the problem even when using a prefab.