How to manage toggle (and other controls) state in a custom inspector?

I have a custom inspector with toggles for a number of items to make it more manageable:

alt text

Each “Item #” can be toggled (simulating the Unity array inspector). The toggles are only part of the editor itself and exist only to make the editor more easy to digest. Unfortunately since there is no boolean in my object representing the toggle state it means that all the toggles reset as I switch between objects in Unity.

I could solve this issue by putting a variable for the toggle state into my object but this seems wasteful and unnecessary.

I know that Unity has some method of handling this without intruding into the object itself because the default inspector toggles work correctly with no “extra” state variables in the object.

How can I get Unity to remember the toggle state?

Just add a boolean array to your inspector. When you size your array you have to size this array as well. You could make the array a static variable, so the toggled items keep their state when selecting different objects.

OnEnable is fired when you select one of your objects. You should check and update the array here. I would use a List<> instead of an array :wink: just because it’s easier to resize.

My solution was similar to Bunny83’s. I have an array for the boolean flags for each element, but I save the flags to editor prefs. This code is first pass, and needs some polish, but goes something like this:

public MyType thisTarget;
public bool[] displaysExpanded = new bool[0];

void OnEnable () {
	thisTarget = target as MyType;
	displaysExpanded = new bool[thisTarget.myArrayOrList.Length];
	for (int i = 0; i < displaysExpanded.Length; i++) {
		displaysExpanded *= EditorPrefs.GetBool ("FoldFlag"+i);*
  •   }*
  • }*

  • void OnDisable () {*

  •   for (int i = 0; i < displaysExpanded.Length; i++) {*

_ EditorPrefs.SetBool (“FoldFlag”+i, displaysExpanded*);_
If you wanted to save this per game object, you could have the editor prefs key be something like “FoldFlag” (or whatever is legal).