Custom Editor - Values not being retained.

I’ve searched the forums and found what looked like answers to my question but they don’t seem to work for my case. I think I’m missing something simple.

I’m trying to create a simple custom editor that will allow me to change the z-value of the transform by selecting a fixed value from a drop down. What I have works great except for the fact that it is not maintaining the selected value when I play or when I select off and back on to the object.

Note, this is related to my Unity Answers question here.

Here is my code:

//dummy component so I can add custom editor to specific game objects.
[ExecuteInEditMode]
public class DepthSetter : MonoBehaviour {
}

//custom editor to create a drop down list of values and default to "0" (index=2)
//for some reason the index value is not preserved on play or upon deselecting/reselecting object.
[CustomEditor (typeof (DepthSetter))]
public class DepthSetterEditor : Editor {
	SerializedObject depthSetter;
	private Transform _transform;	
	
	[SerializeField]
	public int index = 2;
	
	string[] depths = {"-.02", "-.01", "0", ".01", ".02"};
	
	public override void OnInspectorGUI () 
	{
		_transform = ((DepthSetter)target).gameObject.transform;		
		
		index = EditorGUILayout.Popup("Depth",index,depths);		
		
		if (GUI.changed)
		{
			float z = float.Parse(depths[index]);
			_transform.localPosition = this.FixIfNaN(new Vector3(_transform.localPosition.x, _transform.localPosition.y, z));
		}
	}
	
	private Vector3 FixIfNaN (Vector3 v)
	{
		if (float.IsNaN(v.x))
		{
			v.x = 0;
		}
		if (float.IsNaN(v.y))
		{
			v.y = 0;
		}
		if (float.IsNaN(v.z))
		{
			v.z = 0;
		}
		return v;
	}
}

you can achieve your goal by making the index variable static; ie

// change this definition
//public int index = 2;
// into this
static int index;

Store the index in your depthsetter class. Editor values are not saved. The serializefield attribute does nothing in an editor class.

FYI, here is the final solution I went with:

http://answers.unity3d.com/questions/424839/how-to-create-custom-editor-component-to-set-z-pos.html#answer-425843

Thanks for the help everyone.