原理是很简单的,在txt文件中写入账号和密码,在写一个记住密码的状态.
通过解析txt文件来读取状态
然后写一段简单易懂的代码:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoginToTheGame : MonoBehaviour
{
public InputField userName; //用户名输入框
public InputField password; //密码输入框
public Toggle rememb; //记住密码选项
public Button enterInto; //确定登录按钮
string name; //从文件中解析出来的账号
string pwd; //从文件中解析出来的密码
bool thisTimeRem = false; //本次登录是否记住密码
bool lastTimeRem = false; //上次登录是否记住密码
bool complement = false; //是否进行补全
// Start is called before the first frame update
void Start()
{
string line = File.ReadAllText("User.txt"); //解析txt文件
string[] infos = line.Split('|'); //分割字符串
name = infos[0]; //第一段为账号
pwd = infos[1]; //第二段为密码
if (infos[2] == "T") //判断上次是否记住密码
{
lastTimeRem = true;
}
//按钮监听
enterInto.onClick.AddListener(() =>
{
//判断本次是否记住了密码
if (thisTimeRem)
{
//判断账号是否输入正确
if (userName.text == name && password.text == pwd)
{
//写入新的信息覆盖原本的信息
string str = name + "|" + pwd + "|" + "T";
File.WriteAllText("User.txt", str);
//密码正确跳转场景
SceneManager.LoadScene("SampleScene");
}
else
{
//Console中输出错误信息
print("账号或者密码错误!");
}
}
else
{
if (userName.text == name && password.text == pwd)
{
//写入新的信息覆盖原本的信息
string str = name + "|" + pwd + "|" + "F";
File.WriteAllText("User.txt", str);
//密码正确跳转场景
SceneManager.LoadScene("SampleScene");
}
else
{
//Console中输出错误信息
print("账号或者密码错误!");
}
}
});
}
// Update is called once per frame
void Update()
{
//判断上次是否记住密码
if (lastTimeRem)
{
//查找用户名是否匹配,是否进行补全
if (userName.text == name && complement==false)
{
//自动补全密码
password.text = pwd;
//自动勾选"记住密码"选项
StartCoroutine(ExecuteOnce());
complement = true;
}
}
//判断账户和密码是否匹配
if (userName.text == name && password.text == pwd)
{
//判断"记住密码"选项是否勾选
if (rememb.isOn)
{
//更新状态信息
thisTimeRem = true;
}
}
}
}
如果有多条账号,可以在文件的读取和写入的地方稍作更改