Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

そのやり方を幾つかのメモ。
(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 () {
    }
}
YuwUnknown
iOSアプリ作ってます!ブログもやってるんで、是非見に来てください( ̄▽ ̄)
http://project-unknown.hatenablog.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした