LoginSignup
91
85

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-04-11

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

そのやり方を幾つかのメモ。
(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 static int hitpoint = 0;
    void Start() {
        DontDestroyOnLoad(this);
    }
}

/// -----------------------------------------
/// Result Scene
/// -----------------------------------------

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

    void Update () {
    }
}
91
85
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
91
85