Unity/Csharp/端末変数保存
提供: 初心者エンジニアの簡易メモ
目次
保存/取得
保存
PlayerPrefs.SetInt(string key, int num); PlayerPrefs.SetFloat(string key, float x); PlayerPrefs.SetString(string key, string str);
取得
int num = PlayerPrefs.GetInt(string key, int default); float x = PlayerPrefs.GetFloat(string key, float default); string str = PlayerPrefs.GetString(string key, string default);
PlayerPrefsにBoolはないので作る
public static bool GetBool(string key, bool defalutValue){ var value = PlayerPrefs.GetInt(key, defalutValue ? 1 : 0); return value == 1; } public static void SetBool(string key, bool value){ PlayerPrefs.SetInt(key, value ? 1 : 0); }
参考:http://smartgames.hatenablog.com/entry/2016/08/22/010140
PlayerPrefsにdoubleがないので作る
// double start public static void SetDouble(string key, double value) { PlayerPrefs.SetString(key, DoubleToString(value)); } public static double GetDouble(string key, double defaultValue) { string defaultVal = DoubleToString(defaultValue); return StringToDouble(PlayerPrefs.GetString(key, defaultVal)); } public static double GetDouble(string key) { return GetDouble(key, 0d); } private static string DoubleToString(double target) { return target.ToString("R"); } private static double StringToDouble(string target) { if (string.IsNullOrEmpty(target)) return 0d; return double.Parse(target); } // double end
参考:https://forum.unity.com/threads/saving-a-double-with-playerprefs.89879/
editer上のデータ削除
Editor/Clear All PlayerPrefs
参考:https://pandoraxssscan-929.hatenablog.com/entry/2020/09/06/223037
getとsetの場合
string viewCntKey = "viewCntKey"; int viewCntDefault = 0; public int ViewCnt { get { return PlayerPrefs.GetInt(viewCntKey, viewCntDefault); } set { PlayerPrefs.SetInt(viewCntKey, value); } } ViewCnt = 1; // 設定 Debug.Log(ViewCnt); // 取得
Editorで削除
Unityメインメニュー/Edit/ClearAllPlayerPrefs