LoginSignup
1
1

More than 5 years have passed since last update.

Unity 異なるシーンで変数を共有する簡単な方法

Last updated at Posted at 2018-09-27

Unity初心者のメモ

私がOculus Goで動くコンテンツを作成していて、「ゲームシーンで保持しているスコアをリザルトシーンに出したい!」と思ったときに実践した方法です。
なおC#で記述しております。

やり方

共有する変数を static publicで宣言します。簡単。
例えばゲームシーンでスコアを計算し、ゲームが終わったらリザルトシーンに遷移してスコアを表示するようにします。

Game.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Game : MonoBehaviour {
  public static float score = 0;       // スコア

  void Start () {
  }

  void Update () {
  // コントローラーのトリガーを押したらスコアが加算される
    if(OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)){
      score += 100;
    }
  }

  public static float getScore(){
    return score;
  }
}

コントローラーのトリガーが押されたら100スコアが加算されるとします。
public static float scoreで共有したい変数を宣言し,
値を取得する用のメソッドをpublic static float getScore()のように記述します。

Result.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Result : MonoBehaviour {

  void Start () {
    // ログ出力
    Debug.Log("Score: "+ Game.getScore());
  }

  void Update () { 
  }
}

参照したい別のシーンのクラスでは、Game.getScore()のようにクラス.メソッドの形でアクセスすれば、100ずつ加算された結果を参照することが出来ます。

注意

複雑な構造の場合や、色々な箇所から参照される場合には注意が必要です。
「クラス変数」にしたため、インスタンスを生成せずとも参照できてしまうので、他のすべての参照している箇所に影響が出ます。
単方向への参照など、シンプルな場合に使うのが良いです。

1
1
1

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
1
1