1、首先了解下 Unity 的 PlayerPrefs 存儲
目前,在 Unity 中只支持 int、string、float 三種數據類型的讀取,所以我們可以使用這三種數據類型來存儲簡單的數據
而其中用於數據持久化的類為 PlayerPrefs,如下:
數據保存
-
PlayerPrefs.SetString(“Name”,Key.value);
-
PlayerPrefs.SetInt(“Name”,Key.value);
-
PlayerPrefs.SetFloat(“Name”,Key.value);
數據讀取
-
PlayerPrefs.GetString(“Name”);
-
PlayerPrefs.GetInt(“Name”);
-
PlayerPrefs.GetFloat(“Name”);
2、創建好登錄、注冊以及登錄成功的頁面,添加輸入框、提示框和相應的控件
3、注冊&登錄代碼:
1 using UnityEngine; 2 using UnityEngine.UI; 3 4 /// <summary> 5 /// 登錄/注冊 6 /// </summary> 7 public class SignIn_Up : MonoBehaviour 8 { 9 // 登錄成功頁面 10 public GameObject signSucceed; 11 12 // 注冊頁面 13 public GameObject signUp; 14 public InputField upUserName; 15 public InputField upPassword; 16 public InputField passwordAgain; 17 public Text upTips; 18 19 // 登錄頁面 20 public GameObject signIn; 21 public InputField inUserName; 22 public InputField inPassword; 23 public Text inTips; 24 25 bool didSignedUp = false; 26 bool didSignedIn = false; 27 28 void Update() 29 { 30 if (didSignedUp) 31 { 32 didSignedUp = false; 33 upTips.text = "注冊成功,請返回到登錄頁面登錄!"; 34 Debug.Log("注冊成功,跳轉到登錄頁面"); 35 } 36 if (didSignedIn) 37 { 38 didSignedIn = false; 39 Debug.Log("登錄成功,跳轉到登錄成功頁面"); 40 signSucceed.SetActive(true); 41 signIn.SetActive(false); 42 } 43 } 44 45 public void OnBackClicked() // 注冊頁面返回按鈕 46 { 47 signIn.SetActive(true); 48 signUp.SetActive(false); 49 } 50 51 public void OnUpSignUpClicked() // 注冊頁面注冊按鈕 52 { 53 var pass = passwordAgain.text.Trim(); 54 55 if (!upPassword.text.Trim().Equals(pass)) 56 { 57 upTips.text = "兩次輸入的密碼不一致,請重新輸入!"; 58 return; 59 } 60 else if (upUserName.text.Trim() == "" || upPassword.text.Trim() == "" || pass == "") 61 { 62 upTips.text = "用戶名密碼不能為空,請重新輸入!"; 63 return; 64 } 65 else 66 { 67 PlayerPrefs.SetString(upUserName.text, upPassword.text); // 以用戶名為鍵名進行存儲 68 Debug.Log("用戶名:" + upUserName.text); 69 Debug.Log("密碼:" + upPassword.text); 70 OnBackClicked(); 71 } 72 } 73 74 public void OnSignInClicked() // 登錄頁面登錄按鈕 75 { 76 if (inUserName.text.Trim() == "" || inPassword.text.Trim() == "") 77 { 78 inTips.text = "用戶名密碼不能為空,請重新輸入!"; 79 } 80 else if (PlayerPrefs.GetString(inUserName.text.Trim()) == null) 81 { 82 inTips.text = "用戶不存在!請注冊后再登錄!"; 83 } 84 else if (PlayerPrefs.GetString(inUserName.text.Trim()) != inPassword.text.Trim()) 85 { 86 inTips.text = "用戶密碼錯誤,請重新輸入!"; 87 } 88 else 89 { 90 didSignedIn = true; 91 } 92 } 93 94 public void OnInSignUpClicked() // 登錄頁面注冊按鈕 95 { 96 signUp.SetActive(true); 97 signIn.SetActive(false); 98 } 99 100 public void OnQuitClicked() // 登錄成功頁面退出按鈕 101 { 102 Application.Quit(); 103 UnityEditor.EditorApplication.isPlaying = false; 104 } 105 }
4、測試效果