Search Unity

Save TreeViewState when closing and re-opening the editor window?

Discussion in 'Immediate Mode GUI (IMGUI)' started by Xarbrough, Oct 6, 2020.

  1. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    I'm using the TreeViewAPI to draw within a custom editor window. I've implemented the TreeViewState as shown in the documentation and it saved the expanded state and selection through playmode. However, when I close my window and re-open it, the state is lost (of course).

    How does Unity normally save the view state across sessions? I'd like to have the tree view open the same way the user left the window the last time, if possible (number of columns and rows match, etc.).

    I thought about using EditorPrefs combined with EditorJsonUtility. Is this the recommended way?

    In the new UI Toolkit, controls have a viewDataKey and Unity seems to implement more of this persistence internally, so this is why I'm asking if I even have to handle this myself or can use some editor system.
     
  2. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    Btw, I've gone with the EditorPrefs and JsonUtility approach and it works fine. I just thought that there might be some higher-level API for this task.

    Code (CSharp):
    1. bool firstInit = false;
    2.  
    3. if (treeViewState == null)
    4. {
    5.     string json = EditorPrefs.GetString("AdventureWindow.TreeViewState", string.Empty);
    6.     if (json != string.Empty)
    7.         treeViewState = JsonUtility.FromJson<TreeViewState>(json);
    8.  
    9.     if (treeViewState == null)
    10.         treeViewState = new TreeViewState();
    11.  
    12.     firstInit = true;
    13. }