Call inspector editor script function from another editor script

Hi,

[CustomEditor (typeof(TestClass))]

public class TestClassEditor : Editor
{
	float a = 1;
	float b = 2;
	public void sum ()
	{
		Debug.Log (a + b);
	}
	
	public override void OnInspectorGUI ()
	{
		a = EditorGUILayout.FloatField (a);
		b = EditorGUILayout.FloatField (b);
		if (GUI.Button(new Rect(20, 300, 100, 30), new GUIContent("sum")))
			sum ();
	}
}

In editor i can select gameobject and click on “sum” button, but I want to do this (call sum function) from another editor script.

e.g I could access to the game object with this code in another editor script:

GameObject obj = GameObject.Find ("object name");
obj.GetComponent <TestClass> (); // not TestClassEditor

but I want to do something like this:

GameObject obj = GameObject.Find ("object name");
obj.GetComponent <TestClassEditor> ().sum ();

Any idea?

Thanks

You have to get a reference to your Editor-instance. Keep in mind that it’s possible that there is none or multiple (since you can open multiple Inspectors). With Resources.FindObjectsOfTypeAll you can search for any instances that currently exist.

TestClassEditor editors = (TestClassEditor[])Resources.FindObjectsOfTypeAll(typeof(TestClassEditor));
if (editors.Length >0)
{
    editors[0].sum();
}

This will execute the sum function of the first instance it can find.

static function.

public class Operate {
   public static void Sum( int a, int b ) {
      Debug.Log( a + b );
   }
}

To use it:

if (GUI.Button(new Rect(20, 300, 100, 30), new GUIContent("sum"))) {
   Operate.Sum( a, b );
}