ゲーム化!tomo_manaのブログ

ゲーム化!tomo-manaのブログ

Unityでゲームを作る方法について紹介しています

Unity学習#34 複数シーン構成でのイベントシステムの切り替え (Unity 2019.4.4f1)

戦闘シーンの実装にあたって、イベントシステムはこれまでと同じ作り方でよいか迷ったので、先にゲームを複数シーンで構成する時の、イベントシステムの切り替えについて調べました。

複数シーンでのイベントシステムの切り替え

EventSystem を切り替えるには、EventSystem.current に、現在選択されているシーンの EventSystem を代入します

通常は、加算シーンで立ち上げておいて、アクティブなシーンを切り替えるタイミングで、EventSystem を切り替えます。この時、Camera(Transform系) と Canvas(RectTransform系)も併せて無効化します。また、EventSystem と連動して動く PlayerInput も無効化します。

コード

以下は、EventSystem、Camera、Canvas、PlayerInput がいずれも階層の一番上(Root)に属している場合のコードです。

static void ActivateSceneObjects(Scene scene)
{
    ForceSceneActivateState(scene, true);
}
static void DeactivateSceneObjects(Scene scene)
{
    ForceSceneActivateState(scene, false);
}
static void ForceSceneActivateState(Scene scene, bool state)
{
    GameObject[] gameObjects = scene.GetRootGameObjects();
    
    // カメラ
    foreach( GameObject g in gameObjects ){
        if( g.GetComponent<Camera>() != null ){
            g.SetActive(state);
            break;
        }
    }

    // イベントシステム
    foreach( GameObject g in gameObjects ){
        if( g.GetComponent<EventSystem>() != null ){
            g.SetActive(state);
            if( state == true ){
                // イベントシステムの切り替え
                EventSystem.current = g.GetComponent<EventSystem>();
            }
            break;
        }
    }

    // プレイヤーインプット
    foreach( GameObject g in gameObjects ){
        if( g.GetComponent<PlayerInput>() != null ){
            g.SetActive(state);
            break;
        }
    }

    // キャンバス
    foreach( GameObject g in gameObjects ){
        if( g.GetComponent<Canvas>() != null ){
            g.SetActive(state);
            break;
        }
    }
}

関連記事

EventSystem と InputSystemUIInputModule の関係

※作成中

EventSystem、InputSystemUIInputModule と PlayerInput

※作成中

InputUser と InputDevice/Control

※作成中

(以上)