unityでシーン間で変数を保持する方法

scoreManagerというCSとresultscoreManagerというCSがあるとする。

scoreManagerのmyTextをシーンが変わっても渡す方法。

①ScoreManagerでmyTextをstaticとして定義する。

②staticなものはunityのエディタで指定できない。(アタッチなどができない)。

③よって、awake関数でmyText = GameObject.Find(“scoreText”).GetComponent<Text>();などと動的にオブジェクトを指示する必要がある。

ScoreManager

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

public class scoreManager : MonoBehaviour
{
public static Text myText; // Unityエディタから設定するTextコンポーネント


void Awake()
{
    myText = GameObject.Find("scoreText").GetComponent<Text>();
}

void Start()
{
    // テキストを初期化
    myText.text = "00000";

}

void Update()
{
    // 何らかの条件でテキストを変更(この例ではスペースキーが押されたら)
    if (Input.GetKeyDown(KeyCode.Space))
    {
        ChangeText();
    }
}

// テキストを変更する関数
void ChangeText()
{
    myText.text = "12345";
}

}

resultScoreManager

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

public class resultScoreManager : MonoBehaviour
{

public Text resultScore ;
// Start is called before the first frame update
void Start()
{
    resultScore.text = scoreManager.myText.text;
}

}

この記事が気に入ったら
フォローしてね!

コメント

コメントする

目次