From 1251a75f843c15cbcd58e444e692b707e7634ceb Mon Sep 17 00:00:00 2001 From: bd_ Date: Sat, 3 Aug 2024 20:35:18 -0700 Subject: [PATCH] fix: TogglablePreviewNode.Create can't be used in static init (#310) --- Editor/PreviewSystem/TogglablePreviewNode.cs | 27 +++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/Editor/PreviewSystem/TogglablePreviewNode.cs b/Editor/PreviewSystem/TogglablePreviewNode.cs index c7c65e35..622c998f 100644 --- a/Editor/PreviewSystem/TogglablePreviewNode.cs +++ b/Editor/PreviewSystem/TogglablePreviewNode.cs @@ -1,5 +1,6 @@ using System; using nadena.dev.ndmf.preview.UI; +using UnityEditor; namespace nadena.dev.ndmf.preview { @@ -8,6 +9,14 @@ namespace nadena.dev.ndmf.preview /// public sealed class TogglablePreviewNode { + private static bool IN_STATIC_INIT = true; + + [InitializeOnLoadMethod] + private static void Init() + { + EditorApplication.delayCall += () => IN_STATIC_INIT = false; + } + /// /// The name that will be shown to the user. Will be re-invoked on language change. /// @@ -22,7 +31,7 @@ private TogglablePreviewNode(Func displayName, bool initialState) } /// - /// Creates a togglable preview node. Must not be invoked during static initialization. + /// Creates a togglable preview node. /// /// A function which returns the localized display name for this switch /// If not null, a name which will be used to save this configuration @@ -30,12 +39,22 @@ private TogglablePreviewNode(Func displayName, bool initialState) public static TogglablePreviewNode Create(Func displayName, string qualifiedName = null, bool initialState = true) { - if (qualifiedName != null) initialState = PreviewPrefs.instance.GetNodeState(qualifiedName, initialState); - var node = new TogglablePreviewNode(displayName, initialState); + if (qualifiedName != null) - node.IsEnabled.OnChange += value => PreviewPrefs.instance.SetNodeState(qualifiedName, value); + { + EditorApplication.CallbackFunction loadSaved = () => + { + node.IsEnabled.Value = PreviewPrefs.instance.GetNodeState(qualifiedName, initialState); + node.IsEnabled.OnChange += value => PreviewPrefs.instance.SetNodeState(qualifiedName, value); + }; + + if (IN_STATIC_INIT) + EditorApplication.delayCall += loadSaved; + else + loadSaved(); + } return node; }