Editor scripting: Accessing the script's instance

Hello everyone.

I’ve started learning a little bit of editor scripting, as I’ve seen it’s an easy en elegant way of doing things for my game. I’ve followed some tutorials and learned how to do a simple editor script which changes the inspector window for a script or component. I’m extending the editor class, and using [CustomEditor( typeof(MyScript) )], to specify that this will be what’s shown at this script’s inspector instead of the default script inspector.

The whole point of doing this (although is not very important to what I’m asking) is to make an NPC “pseudo-editor”, so the script MyScript just contains a couple of generic lists (or List< T >) of a class “NPC”. My goal is being able to add more NPCs (instances of the class NPC) to any of the lists from within the editor (so selecting an npc type, and some of the stats in something like a form), and then being able to select previous elements for the list and modify them.

As far as I know, it shouldn’t be difficult with the GUILayout controls to easily build a nice GUI for this, and the functionality I’m trying to implement is not that hard, but I’m having a hard time trying to figure out how can I access the script which I’m creating the inspector for, from my editor script.

So, to explain myself, my script is called NPC_Array, and my editor script NPC_Adder. From NPC_Adder, I want to access the instance of NPC_Array this editor script is currently working on. Just like when I use the “this” keyword for a class, but it has to be something different as this would refference the editor script, not the NPC_Array class (which, if it’s of any help, inherits from MonoBehaviour, although otherwise it couldn’t have an inspector window wouldn’t it?)

Any help on this will be much appreciated, as well as some comments about faster or easier (or fancier) ways to accomplish what I’m trying to do through editor scrpting, which seems to be a whole new world to me.

Thank you very much

You want the target? :wink:

Keep in mind that yourNPC_Array script have to contain serializable constructs and the variables need to be public. The serialization doesn’t support inheritance. I guess the NPC class is a simple class with an Serializable attribute? In this case it should work, good luck.

Normally you can do something like this:

[CustomEditor (typeof(NPC_Array))]
public class NPC_Adder : Editor 
{
  // Class here
}

That means that the NPC_Adder, which is a editor script, is connected to your MonoBehaviour script NPC_Array. Now you can use SerializedProperty to set and retrieve data to and from the NPC_Array script in your custom inspector.

Good luck!