うにてぃブログ

UnityやUnreal Engineの記事を書いていきます

【Unity】UnityEditor の再生、停止、一時停止をハンドルする

Unity 2017.3以降

EditorApplication.playModeStateChangedEditorApplication.pauseStateChanged
を利用することで各種タイミングに合わせて処理をすることができます

using UnityEditor;
using UnityEngine;

public static class SamplePlayModeStateChangeObserver
{
    [InitializeOnLoadMethod]
    private static void Init()
    {
        EditorApplication.playModeStateChanged += PlayModeStateChanged;
        EditorApplication.pauseStateChanged += PauseStateChanged;
    }
 
    private static void PauseStateChanged(PauseState state)
    {
        switch (state)
        {
            case PauseState.Paused:
                Debug.Log("Pause");
                break;
            case PauseState.Unpaused:
                Debug.Log("UnPause");
                break;
        }
    }
 
    private static void PlayModeStateChanged(PlayModeStateChange state)
    {
        switch (state)
        {
            case PlayModeStateChange.ExitingEditMode:
                Debug.Log("Press Play Button");
                break;
            case PlayModeStateChange.EnteredPlayMode:
                Debug.Log("Play");
                break;
            case PlayModeStateChange.ExitingPlayMode:
                Debug.Log("Press Stop Button");
                break;
            case PlayModeStateChange.EnteredEditMode:
                Debug.Log("Stop");
                break;
        }
    }
}

Unity 2017.3未満

以前は public static EditorApplication.CallbackFunction playmodeStateChanged; のコールバックのみで

EditorApplication.isPlayingOrWillChangePlaymodeEditorApplication.isPlaying
を利用して頑張って今の状態を知る必要がありました

using UnityEditor;
using UnityEngine;

public static class SamplePlayModeStateChangeObserver
{
    [InitializeOnLoadMethod]
    private static void Init()
    {
        EditorApplication.playModeStateChanged += PlayModeStateChanged;
    }
 
    private static bool _isPause;
 
    private static void PlayModeStateChanged()
    {
        // ポーズ
        if (EditorApplication.isPaused != _isPause)
        {
            Debug.Log("Pause");
        }
        // 再生
        else if (EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)
        {
            Debug.Log("Play");
        }
        // 停止
        else if (!EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
        {
            Debug.Log("Stop");
        }
 
        _isPause = EditorApplication.isPaused;
    }
}