コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】ArgumentException: You can only call GUI functions from inside OnGUI.

概要

using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

public sealed class Example : EditorWindow
{
    [MenuItem( "Tools/Hoge" )]
    private static void Open()
    {
        GetWindow<Example>();
    }

    private async void OnGUI()
    {
        if ( GUILayout.Button( "実行" ) )
        {
            await Task.Run( () => { } );
        }

        GUILayout.Label( "ピカチュウ" );
    }
}

上記のようにエディタ拡張の OnGUI 関数の中で await すると

f:id:baba_s:20210531155029g:plain

ArgumentException: You can only call GUI functions from inside OnGUI.
UnityEngine.GUIUtility.CheckOnGUI () (at <07cfa953d94b44e4bb3a488bef79100a>:0)
UnityEngine.GUI.get_skin () (at <07cfa953d94b44e4bb3a488bef79100a>:0)
UnityEngine.GUILayout.Label (System.String text, UnityEngine.GUILayoutOption[] options) (at <07cfa953d94b44e4bb3a488bef79100a>:0)
Example+<OnGUI>d__1.MoveNext () (at Assets/Editor/Example.cs:20)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <eae584ce26bc40229c1b1aa476bfa589>:0)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) (at <eae584ce26bc40229c1b1aa476bfa589>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <a1ac446df41c4a67becf2f8317dc1792>:0)
UnityEngine.UnitySynchronizationContext:ExecuteTasks()

ボタンを押した時にこのような例外が発生してしまう

await Task.Run( () => { } );
return;

await した後に return すると例外が発生しなくなる