うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】EditorCoroutine で WaitForSeconds を使用できない問題の解決方法

UnityのEditorCoroutineでは、通常のWaitForSecondsを利用することができず、代わりにEditorWaitForSecondsを使用する必要があります。これはUnityのEditor内でのコルーチン処理において、時間の経過を待つための仕組みが異なるためです。

EditorCoroutineを使用する際に、通常のWaitForSecondsを用いると正しく動作しません。そのため、EditorCoroutine内ではEditorWaitForSecondsを利用する必要があります。

以下は、EditorWaitForSecondsを使用したサンプルコードです

using UnityEngine;
using UnityEditor;

public class EditorCoroutineExample : MonoBehaviour
{
    [MenuItem("CoroutineExample/StartCoroutineInEditor")]
    static void StartCoroutineInEditor()
    {
        EditorCoroutineUtility.StartCoroutineOwnerless(MyCoroutine());
    }

    static IEnumerator MyCoroutine()
    {
        Debug.Log("Coroutine started in Editor");
        yield return new EditorWaitForSeconds(3); // EditorWaitForSecondsを利用
        Debug.Log("Waited for 3 seconds in Editor");
    }
}

このサンプルコードでは、EditorCoroutineUtility.StartCoroutineOwnerlessを使用してEditor内でのコルーチン処理を開始し、EditorWaitForSecondsを使用して3秒待機します。

このように、UnityのEditorCoroutineでWaitForSecondsを使用する際には、EditorWaitForSecondsを利用することで正常に動作させることができます。


以下は、EditorWindowを継承した場合にEditorCoroutineとEditorWaitForSecondsを使用するサンプルコードです。

EditorWindowを継承した場合は this.StartCoroutine で EditorCoroutine を開始できます。

using UnityEngine;
using UnityEditor;

public class MyEditorWindow : EditorWindow
{
    [MenuItem("Window/MyEditorWindow")]
    static void ShowWindow()
    {
        GetWindow<MyEditorWindow>("My Window");
    }

    void OnGUI()
    {
        GUILayout.Label("Editor Coroutine Example");

        if (GUILayout.Button("Start Coroutine"))
        {
            this.StartCoroutine(MyCoroutine());
        }
    }

    static IEnumerator MyCoroutine()
    {
        Debug.Log("Coroutine started in EditorWindow");
        yield return new EditorWaitForSeconds(3); // EditorWaitForSecondsを利用
        Debug.Log("Waited for 3 seconds in EditorWindow");
    }
}