Unity シーン間で変数を共有する方法

はじめに

ゆう@あんのうんです。

シーン間で変数をやり取りしたいケースがママあります。 例えば、メインゲームシーンの結果をリザルトシーンで参照したり...

そのやり方を幾つかのメモ。 (SampleはC#です)

static変数でのやり取りする

クラスのメンバ変数をpublic staticで宣言しておくと、他のオブジェクトから参照ができるようになります。

また、これで宣言した変数がゲームを終了させるまで継続して保持されます。

下記SampleはMainGameシーンのhitpoint変数を、Resultシーンで取得しています。

/// -----------------------------------------
/// MainGame Scene
/// -----------------------------------------

public class MainGameController : MonoBehaviour {
    public static int hitpoint = 0;
    
    // getter
    public static int getHitPoint() {
        return hitpoint;
    }
    
    void Start () {
    }

    void Update () {
    }
}
/// -----------------------------------------
/// Result Scene
/// -----------------------------------------

public class ResultController : MonoBehaviour {
    void Start () {
        int resultHitpoint = MainGameController. getHitPoint()
    }

    void Update () {
    }
}

DontDestroyOnLoad()を使う

DontDestroyOnLoadを使うことで、Sceneを切り替えてもGameObjectが破棄されなくなります。

/// -----------------------------------------
/// MainGame Scene
/// -----------------------------------------

public class MainGameController :MonoBehaviour {
    public int hitpoint = 0;
    void Start() {
        DontDestroyOnLoad(this);
    }
}
/// -----------------------------------------
/// Result Scene
/// -----------------------------------------

public class ResultController : MonoBehaviour {
    void Start () {
        int resultHitPoint = MainGameController.hitpoint;
    }

    void Update () {
    }
}