今回はゲーム内で獲得したスコアデータをシーン間で共有してをリザルトシーンで表示させる方法を紹介していこうと思います。
準備
今回は押すとスコアが上がるボタンとそれを表示するテキストを用意します。


シーンをもう一つ用意してそこにはテキストだけ作っておきます。

そしてシーン切り替えを管理するオブジェクトを用意

シーン切り替えの実装方法はこちら↓
スクリプト
それでは、スクリプトを書いていきましょう。
スコアを管理するプログラムはこんな感じ
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ScoreScript : MonoBehaviour
{
TextMeshProUGUI text;
public static int score;// 共有する変数
void Start()
{
score = 0;// スタートでスコアをリセット
// TextMeshProコンポーネントを取得
text = GetComponent<TextMeshProUGUI>();
}
void Update()
{
text.text = score.ToString();// scoreをテキストに適用
}
// スコアを足す
public void AddScore()
{
score++;
}
}
こいつをスコアを表示するテキストにアタッチ

そしてボタンがスコアを上げる関数を呼び出せるようにします。
On Clickに「ScoreScript」を入れてAddScore関数を設定します。


これでボタンを押してスコアを上げれるようになります。
次は移行先のシーンのテキストのスクリプトを書きます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DispScore : MonoBehaviour
{
TextMeshProUGUI scoreText;
void Start()
{
scoreText = GetComponent<TextMeshProUGUI>();// TextMeshProコンポーネントを取得
}
void Update()
{
scoreText.text = ScoreScript.score.ToString();// 共有する変数をTextとして入れる
}
}
このスクリプトを移行先のシーンのテキストにアタッチ

これで実行をしてみますと、
Staticとは
今回のスクリプトのポイントはこいつ
public static int score;// 共有する変数
このscoreをstaticとして宣言することで、どこからでもアクセスすることができます。
だがstaticとは何でしょうか?
staticはクラスが持っている1つしか存在しない値です。
例として「スコア」「生存時間」「倒した敵の数」などがあります。
もしもこれらをリザルトで表示させるために共有する値として宣言したいのならstaticにしましょう。
値にアクセスする場合はこのようにしましょう。
「クラス名.共有する変数」
int score = ScoreScript.score
まとめ
いかがだったでしょうか?
この記事がお役に立てればと思います。