Unity 编辑器使用InitializeOnLoad, 出现Menu xxx can’t be checked because it doesn’t exist
问题
使用InitializeOnLoad属性是, 期望unity打开时, 编辑器自定义的菜单设置为选中/未选中状态, 但是会出现警告, 并且未勾选
using UnityEditor;
[InitializeOnLoad]
public class CheckedExample
{
private const string MenuPath = "Tools/Check";
static CheckedExample()
{
Menu.SetChecked(MenuPath, true);
}
[MenuItem(MenuPath)]
private static void Check()
{
}
}
出现如下警告:
Menu xxx can't be checked because it doesn't exist.
解决
在初始化时等待一些时间后再设置选中状态, 问题解决
using System.Threading.Tasks;
using UnityEditor;
[InitializeOnLoad]
public class CheckedExample
{
private const string MenuPath = "Tools/Check";
static CheckedExample()
{
DelayCall();
}
private static async void DelayCall()
{
await Task.Delay(System.TimeSpan.FromSeconds(0.1f));
Menu.SetChecked(MenuPath, true);
}
[MenuItem(MenuPath)]
private static void Check()
{
}
}