UnityEditorですと再生ボタンを押す時OnApplicationPauseが呼ばれるんですね。
これが原因でAwakeとOnApplicationPauseでLoadElapseDataが2回呼ばれてしまい、変数が初期化されてしまいました。
1日ハマった…
なので#if UNITY_EDITORではLoadElapseData()を呼ばないように使い分けしました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void OnApplicationPause(bool pauseStatus) { //離れる時 if(pauseStatus) SaveToDisc(); //戻る時 else{ #if UNITY_EDITOR //ゲームシーンから再生時OnApplicationPauseが呼ばれてしまうのでLoadElapseData();を呼ばない Debug.Log("OnApplicationPause in UnityEditor"); #else Debug.Log("OnApplicationPause in except UnityEditor"); LoadElapseData(); #endif } } |
原因がわからない場合はとりあえずメソッドの中にログを書いとくと解決の糸口になりますね、勉強になりました。
全体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
private const string SCOREKEY = "Score"; private const string LEVELKEY = "Level"; private const string POINTKEY = "Point"; private const string SAVEDFIRSTRUNKEY = "savedFirstRun"; private int checkFirstRun; public static int Score{private set; get;} private static int _point = 2000; public static int Point{ get{ return _point;} private set{ _point = value;} } private static int _level = 1; public static int Level{ get{ return _level;} private set{ _level = value;} } private bool isLoadedGame = false; void Awake() { LoadElapseData(); if(checkFirstRun == 0) { Point = 2000; Debug.Log("FirstLaunch: Point: " + Point); checkFirstRun = 1; } else{ } } void OnApplicationPause(bool pauseStatus) { //離れる時 if(pauseStatus) SaveToDisc(); //戻る時 else{ #if UNITY_EDITOR //ゲームシーンから再生時OnApplicationPauseが呼ばれてしまうのでLoadElapseData();を呼ばない Debug.Log("OnApplicationPause in UnityEditor"); #else Debug.Log("OnApplicationPause in except UnityEditor"); LoadElapseData(); #endif } } void OnApplicationQuit() { //gamesceneで止めるとなぜかtitleで読み込まれていることになる為、boolを作る if(isLoadedGame) SaveToDisc(); } void SaveToDisc() { Debug.Log("SaveToDisc"); createCharManager.SaveCharDataToDisc(); PlayerPrefs.SetInt( SCOREKEY, Score); PlayerPrefs.SetInt( LEVELKEY,Level); PlayerPrefs.SetInt( POINTKEY, Point); Debug.Log("Point: " + Point + " SaveToDisc"); PlayerPrefs.SetInt( SAVEDFIRSTRUNKEY, checkFirstRun); PlayerPrefs.Save(); } void LoadElapseData() { Debug.Log("LoadElapseData"); Score = PlayerPrefs.GetInt(SCOREKEY); Level = PlayerPrefs.GetInt(LEVELKEY); Point = PlayerPrefs.GetInt(POINTKEY); Debug.Log("Point: " + Point); checkFirstRun = PlayerPrefs.GetInt(SAVEDFIRSTRUNKEY); } |