Unity editor - keeping your foldout from collapsing

Hey there!

I have set up a custom inspector for my player. However, whenever I go in-game all of my foldouts collapse. Is there a way to prevent this?

Here’s the foldout code I use in case in matters:

showCameraInfo = EditorGUILayout.Foldout(showCameraInfo, "Camera settings");

So I usually deal with this by putting the editor data in the MonoBehaviour and surrounding it with #if UNITY_EDITOR /* stuff */ #endif

However, recently I came up with a new idea which I think is better. Like @whydoidoit said, you could use EditorPrefs - but the question is, what key should you use so that the foldout value persists when you, say, reselect your object or trigger an assembly reload?

You have to use a key value that is the same before/after an assembly reload. But what to use? If you’re writing an Editor for example, even the ‘target’ is not the same when an assembly reload happens (a new target is instantiated - so using GetInstanceID is useless)

So what you do, is create an interface:

public interface IUniquelyIdentifiedObject
{
   string ID { get; }
}

And then

public class Whatever : MonoBehaviour, IUniquelyIdentifiedObject
{
   [SerializeField]
   private string id;

   public string ID { get { if (string.IsNullOrEmpty(id)) id = Guid.NewGuid().ToString(); return id;}
}

And so now, we have an id value that persists between assembly reloads, so we could use it in our foldouts keys!

// somewhere in editor code...
string fKey = key + "My foldout";
EditorPrefs.SetBool(fKey, EditorGUILayout.Foldout(EditorPrefs.GetBool(fKey), "Foldout"));

where key is:

private string key
{
   get
   {
      var unique = target as IUniquelyIdentifiedObject;
      return unique == null ? target.GetHashCode().ToString() : unique.ID;
   }
}

I don’t like to use EditorPrefs though. I have a BetterPrefs class which just uses a dictionary of ints-bools and strings-bools.

This method handles foldout values on different target instances well, because different targets means different IDs, which means independent foldout values. The values persist because the ID persists.