###前提・実現したいこと
現在、Unityで画面遷移について勉強しています。
2つのSceneを作成し、片方のSceneで値を保存した変数をもう片方のSceneでも用い、表示したいと考えています。
作成したソースコードはTest.csとReadData.csで、それぞれScene1、Scene2にAddComponentしています。
Test.csは、DBから値をJSONで取得し、動的に作成したボタンに取得した値をTextとして表示しています。
(ボタンには、1月1日 1月2日… と表示されています)
これにより月日が表示されたボタンをクリックすることで、Scene2に遷移します。
Scene2は、Scene1でクリックしたボタンに表示されていた月日を、改めてTextとして表示するSceneです。
###発生している問題・エラーメッセージ
ここで発生している問題は、値は保存されているのですが、クリックしたボタンに表示されている月日の値が、Scene2では別の月日で表示されてしまいます。
###該当のソースコード
Test.cs
using UnityEngine; using System.Collections; using MiniJSON; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Test : MonoBehaviour { [SerializeField] RectTransform prefab = null; public static Test Instance = new Test(); public string PostMonth = string.Empty; public string PostDay = string.Empty; void Start() { StartCoroutine("GetJSON"); } IEnumerator GetJSON() { WWW www = new WWW("http://localhost/~~~.php"); yield return www; if (!string.IsNullOrEmpty(www.error)) { Debug.LogError(string.Format("Fail Whale!\n{0}", www.error)); yield break; } string json = www.text; IList List = (IList)Json.Deserialize(json); foreach (IDictionary year in List) { string Month = (string)year["month"]; string Day = (string)year["day"]; var item = GameObject.Instantiate(prefab) as RectTransform; item.SetParent(transform, false); var text = item.GetComponentInChildren<Text>(); text.text = Month.ToString() + "月" + Day.ToString() + "日"; string month1 = Month.ToString(); string day1 = Day.ToString(); Button button = item.GetComponent<Button>(); if (month1 == "1" && day1 == "1") { Test.Instance.PostMonth = month1; Test.Instance.PostDay = day1; button.onClick.AddListener(() => { SceneManager.LoadScene("NextScene"); }); } if(month1 == "1" && day1 == "2") { Test.Instance.PostMonth = month1; Test.Instance.PostDay = day1; button.onClick.AddListener(() => { SceneManager.LoadScene("NextScene"); }); } } } }
ReadData.cs
using UnityEngine; using UnityEngine.UI; public class ReadData : MonoBehaviour { public Text text; void Start() { text.text = Test.Instance.PostMonth + "月" + Test.Instance.PostDay + "日です。"; } }
###試したこと
【Unity】シーン間でスコアを共有 まとめ
このサイトを参考にstatic変数を用いてデータを保存しましたが、1月1日のボタンを押し、Scene2での表示を確かめると、1月2日です と表示されてしまいます。
1月2日のボタンを押し、Scene2での表示を確かめると、1月2日です と正しく表示されています。
なぜこのような表示となってしまうのでしょうか。
###補足情報(言語/FW/ツール等のバージョンなど)
また、コンソールに
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()
Test:.ctor()
Test:.cctor()
という警告も出ていますが、関係あるのでしょうか。
以上、まだUnityを始めたばかりの初心者であり、理解ができていない中の、拙い説明でございますが、ご教授お願いできませんでしょうか。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/09/14 02:53