Unity 登录注册功能的实现(PlayerPrefs)
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、测试效果