Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9747

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

$
0
0
まず、ゲームスタート時(一番最初のシーン))のシーン遷移で スコア保存用のゲームオブジェクトを作成します。 作成したら下記の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); } } これでスコアが表示されるようになりました!!

Viewing all articles
Browse latest Browse all 9747

Trending Articles