Inheritance And Editor Targets

The core of the problem is that I need an explicit reference to access variables off of the base class. This isn’t an issue if I know exactly what class my custom editor is going to be used on, I’ll just cast the target property inherited from Editor - no biggie.

Issues arise when my custom editor is used on derived classes. Consider the following cases.

public class A
{
    public int IntegerVariable;
}
public class B : A
{

}

We have two classes, Class A and Class B. The custom inspector is written for Class A, but since Class B inherits Class A we also use it for Class B and any other class that may inherit Class A. So imagine this scenario: We add Class B to a gameobject and use the custom editor tailored for Class A. Now we need an explicit reference to Class A so the editor is able to access IntegerVariable. You’d usually do something along the lines of

private Target { get { return (A)this.target; } }

but since ‘this’ is now B, the above code will not work. How do you get a reference to Class A?

I think you can get reference to A with your code. As casting B as A is valid.

Just to clarify with the following classes defined.

A.cs

using UnityEngine;

public class A : MonoBehaviour {
	public int IntegerVariable;
}

B.cs

using UnityEngine;

public class B : A {
	
}

AEditor.cs

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(A), true)]
public class AEditor : Editor {

	public override void OnInspectorGUI ()
	{
		A a = (this.target as A);
		EditorGUILayout.LabelField ("Value: " + a.IntegerVariable);
	}
}

Now. With this setup, if you wanted you wanted to make the class B inspector to duplicate A. Consider using this tag in A:

[CustomEditor(typeof(A), true)]

This will make your Class B have the inspector of EditorA.

If you wanted to extend and add more functionality to the inspector in B. Then extend EditorA to reuse the code and base.OnInspectorGUI()

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(B))]
public class BEditor : AEditor 
{
	public override void OnInspectorGUI ()
	{
		base.OnInspectorGUI ();
	}
}