LoginSignup
0
0

More than 1 year has passed since last update.

シーン遷移時にスコアを引き継ぐ

Posted at

まず、ゲームスタート時(一番最初のシーン))のシーン遷移で
スコア保存用のゲームオブジェクトを作成します。
作成したら下記のScoreDataをアタッチします。

ScoreData
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScoreData : MonoBehaviour
{
    public int Score;

    void Start()
    {
        DontDestroyOnLoad(this.gameObject);  //DontDestroyOnLoadでシーン遷移後も保存出来る
        Score = 0;  //ゲームスタート時のスコア
    }

    public int GetScore()
    {
        return Score;  //スコア変数をResultスクリプトへ返す
    }
}

GameMainシーン
スコア表示を書いたスクリプトに記述

SystemMain
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SystemMain : MonoBehaviour
{
    public int Score;
    public Text ScoreText;
    public ScoreData Sd;

    void Start()
    {
        Score = 0;
       //ScoreDataを見つける。(前シーンでDontDestroyOnLoadの記述をしたため、GameMainでも保持していられる)
        Sd = GameObject.Find("ScoreData").GetComponent<ScoreData>();  
    }

    // Update is called once per frame
    void Update()
    {
        ScoreText.text = string.Format("{0}", Score);  //GameMainシーンでのスコア表示
        Sd.Score = Score;  //ScoreDataの中のScore
    }


}

スコア結果を反映したいシーンへ移動して
元からあるゲームオブジェクトでも新たに作成してもいいので
下記スクリプトをアタッチする。

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

public class Result : MonoBehaviour
{
    private GameObject ScoreMaster;
    private ScoreData Sd;
    public Text tx;
    int Score;

    void Start()
    {
        ScoreMaster = GameObject.Find("ScoreData");  //ScoreDataを見つける
        Sd = ScoreMaster.GetComponent<ScoreData>();

        Score = Sd.GetScore();  //ScoreDataの中のGetScore関数を呼び出す
        //アタッチしたオブジェクトに反映したいテキストを紐づける。
        tx.text = string.Format("Score  {0}", Score);
    }
}

これでスコアが表示されるようになりました!!

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