当前位置:   article > 正文

【Unity项目】登录界面_emc unity默认登录

emc unity默认登录

数据库

登录时验证用户名和密码,使用MySQL数据库管理数据,类中的主要方法也都是使用SQL语句完成。类中还提供两个接口, 一个通过username获取UserInfo ,一个是直接获取到排行榜。
数据库连接类

using System;
using MySql.Data.MySqlClient;
using UnityEngine;


public class MySqlAccess
{
    //连接类对象
    public  MySqlConnection mySqlConnection;
    //IP地址
    private static string host;
    //端口号
    private static string port;
    //用户名
    private static string username;
    //密码
    private static string password;
    //数据库名称
    private static string databaseName;
    public MySqlAccess(string _host,string _port, string _username, string _password, string _databaseName)
    {
        host = _host;
        port = _port;
        username = _username;
        password = _password;
        databaseName = _databaseName;
        OpenSql();
    }
    private void OpenSql()
    {
        try {
            string mySqlString = string.Format("datasource={0};port={1};database={2};user={3};pwd={4};"
                , host, port, databaseName, username, password);
            //Debug.Log(mySqlString);
            mySqlConnection = new MySqlConnection(mySqlString);
            mySqlConnection.Open();
        } catch (Exception e) {
            throw new Exception("服务器连接失败,请重新检查MySql服务是否打开。" + e.Message);
        }
    }
}

  • 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

数据库管理类

using System;
using System.Collections.Generic;
using Frame.Utility;
using Game.bean;
using Game.Interface;
using MySql.Data.MySqlClient;
using UnityEngine;
using EventType = Frame.Utility.EventType;

namespace Game
{
    public class DataBaseManager : SingleTonMonoAuto<DataBaseManager>, IDataBaseManager
    {
        private MySqlAccess mySqlAccess;
        private string _connectionStr;
        private MySqlConnection _connection;
        private MySqlCommand  _command;
        Dictionary<string, UserInfo> _dictionary = new Dictionary<string, UserInfo>();
        private UserInfo _userCache;
        //宿舍的ip
        //private string host = "172.20.177.212";
        //课室的
        private string host = "10.9.72.192";

        private void OnEnable()
        {
            EventCenter.Instance.AddListener(EventType.ResetLogin,ResetLogin);
        }

        public void AddMoneyAndHonor(string name,int money,int honor)
        {
            if (_dictionary.ContainsKey(name))
            {
                UserInfo userInfo = _dictionary[name];
                userInfo.money += money;
                userInfo.honor += honor;
                SaveInfo(userInfo);
            }
        }
        
        /// <summary>
        /// 保存UserInfo数据
        /// </summary>
        /// <param name="userinfo"></param>
        public void SaveInfo(UserInfo userinfo)
        {
            int userId = userinfo.id;
            int money = userinfo.money;
            int honor = userinfo.honor;
            string heroList = userinfo.ownedHero;
            if ( !_dictionary.ContainsKey(userinfo.username))
            {
                //把用户数据存入字典
                _dictionary.Add(userinfo.username, userinfo);
            }
            UpdateUserInfo(userId, money, honor, heroList);
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="money"></param>
        /// <param name="honor"></param>
        /// <param name="ownedHero"></param>
        private void  UpdateUserInfo(int @ID,int @money,int @honor,string @ownedHero)
        {
            _command.CommandText = "Update CustomerInfo Set money=\'"
                                   +money+"\', honor=\'"+honor+"\', ownedHero=\'"
                                   +ownedHero+"\' where ID="+ID;
            int i = _command.ExecuteNonQuery();
            Debug.Log("产生影响"+ i);
        }
        
        private DataBaseManager()
        {
            //Debug.Log("DataBaseManager实例化");
            InitDataBase();
        }

        //初始化数据库
        private void InitDataBase()
        {
            mySqlAccess = new MySqlAccess(host,"3306","root","123456","dbcustomerinfo");
            _connection = mySqlAccess.mySqlConnection;
            _command = _connection.CreateCommand();
            SaveInDic();
            
        }

        private void SaveInDic()
        {
            _command.CommandText = "Select * From CustomerInfo";
            MySqlDataReader _reader = _command.ExecuteReader();
            //将数据传入字典
            while (_reader.Read())
            {
                object id = _reader.GetValue(0);
                object username = _reader.GetValue(1);
                object password = _reader.GetValue(2);
                object money = _reader.GetValue(3);
                object honor = _reader.GetValue(4);
                object ownedHero = _reader.GetValue(5);
                object isLogined = _reader.GetValue(6);
                if (!_dictionary.ContainsKey((string) username))
                {
                    _dictionary.Add((string) username,
                        new UserInfo(Convert.ToInt32(id), (string) username, (string) password, Convert.ToInt32(money),
                            Convert.ToInt32(honor), (string) ownedHero ,Convert.ToInt32(isLogined)));
                }
            }
            _reader.Close();
        }
        /// <summary>
        /// 通过用户名获取UserInfo
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public UserInfo GetUserInfo(string name, string pwd)
        {
            _command.CommandText = "Select * From CustomerInfo where username = " + "'" + name + "'";
            if (_command.ExecuteScalar() == null)
            {
                Debug.Log("用户名不存在");
                //用户名不存在
                return null;
            }
            else //用户名存在
            {
                //判断是否与密码匹配
                UserInfo _user;
                _dictionary.TryGetValue(name, out _user);
                if (_user != null && !CheckIsLogined(name))
                {
                    bool pwdIsSame = _user.password == pwd ? true : false;
                    if (pwdIsSame)
                    {
                        Debug.Log("登陆成功");
                        _user.isLogined = 1;
                        _command.CommandText = "UPDATE customerinfo SET islogined = 1 WHERE username = " +"'" + name + "'";
                        _command.ExecuteNonQuery();
                        _userCache = _user;
                        return _user;
                    }
                    else
                    {
                        Debug.Log("账户名或密码错误");
                        return null;
                    }
                }
            }
            return null;
        }

        private bool CheckIsLogined(string username)
        {
            _command.CommandText = "SELECT islogined from customerinfo WHERE username =" + "'" + username + "'";
            object obj = _command.ExecuteScalar();
            bool isLogined = Convert.ToInt32(obj) == 1 ? true : false;
            return isLogined;
        }
        
      
        /// <summary>
        /// 获取排行榜
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public List<UserInfo> GetRankList(int num)
        {
            if (num > _dictionary.Count)
            { 
                Debug.LogError("查询范围超出!");
                return null;
            }
            List<UserInfo> rankList = new List<UserInfo>();
            //排序的SQL语句
            _command.CommandText = "Select * from CustomerInfo ORDER BY honor DESC , money DESC limit " + num;
            MySqlDataReader _reader = _command.ExecuteReader();
            while (_reader.Read())
            {
                UserInfo _userInfo;
                _dictionary.TryGetValue((string) _reader.GetValue(1), out _userInfo);
                rankList.Add(_userInfo);
            }
            _reader.Close();
            return rankList;
        }

        private void OnApplicationQuit()
        {
            //Debug.Log("关闭数据库连接");
            if (mySqlAccess.mySqlConnection!=null)
            {
                EventCenter.Instance.RemoveListener(EventType.ResetLogin,ResetLogin);
                if(_userCache!=null){
                    _userCache.isLogined = 0; 
                    _command.CommandText = "UPDATE customerinfo SET islogined = 0 WHERE username = " +"'" + _userCache.username + "'";
                    _command.ExecuteNonQuery();
                }
                mySqlAccess.mySqlConnection.Close();
            }
        }

        /// <summary>
        /// 一键还原所有登录
        /// </summary>
        public void ResetLogin()
        {
            _command.CommandText = "Update customerInfo Set islogined = 0";
            _command.ExecuteNonQuery();
            print("已还原所有登录");
        }
    }
}
  • 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
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217

登录页面

using System;
using DG.Tweening;
using Frame.UI;
using Frame.Utility;
using Game;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using EventType = Frame.Utility.EventType;

public class LoginModule : UIModuleBase
{
    private InputField inputName;
    private InputField inputPsw;
    private EventSystem _system;
    private bool isSelectUsername; //选框用户名
    private Image FocusLigthUsername;
    private Image FocusLigthPassword;
    private Text txtMention; //密码错误提示

    //可选对象
    Selectable cur = null;

    private void Start()
    {
        _system = EventSystem.current;
        txtMention = FW("txtMention#").Text;
        inputName = FW("Field-UserName#").InputField;
        inputPsw = FW("Field-UserPassword#").InputField;
        FW("LoginButton#").Button.onClick.AddListener(() =>
        {
            Debug.Log("点击了登录按钮 name=" + inputName.text + " psw=" + inputPsw.text);
            //调用UIEvent的事件
            UIEvent.LoginClick(inputName.text, inputPsw.text);
        });    
    }

    
    public void PlayMentionAnime()
    {

        Debug.Log("PlayMentionAnime");
        Tweener _tweener = txtMention.DOFade(1, 0.6f);
        
        _tweener.SetDelay(0);
        _tweener.SetEase(Ease.Linear);
        _tweener.SetAutoKill(true);
        _tweener.SetLoops(0);
    }


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Tab))
        {
            Selectable next = null;
            cur = _system.currentSelectedGameObject.GetComponent<Selectable>();
            print("name=" + cur.name);
            if (cur.name == "Field-UserName#")
            {
                isSelectUsername = true;
                next = cur.FindSelectableOnDown();
            }
            else
            {
                isSelectUsername = false;
                next = cur.FindSelectableOnUp();
            }

            _system.SetSelectedGameObject(next.gameObject, new BaseEventData(_system));
        }

        if (Input.GetKeyDown(KeyCode.Return))
        {
            UIEvent.LoginClick(inputName.text, inputPsw.text);
        }
        if (Input.GetKeyDown(KeyCode.B))
        {
            //一键清空登录状态
            EventCenter.Instance.Call(EventType.ResetLogin);
        }
    }
}
  • 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
  • 81
  • 82
  • 83

登录成功界面

using System;
using System.ComponentModel.Design;
using Frame.UI;
using Game;
using Game.bean;
using Photon.Pun;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
using Object = System.Object;

public class LoginSucPanel : UIModuleBase
{
   private Button BtnCheck;
   private Text LoginMsg;
   protected override void Awake()
   {
      base.Awake();
      BtnCheck = FW("BtnCheck#").Button;
      LoginMsg = FW("txtLoginMsg#").Text;
      
      BtnCheck.onClick.AddListener(() =>
      {
         UIEvent.ToMain();
      });
    }

   
   public void Init()
   {
      LoginMsg.text = "亲爱的"+"\n" +  PhotonNetwork.NickName +"\n"+ "欢迎进入游戏!";
   }

   public override void OnSpawn(Object obj)
   {
      base.OnSpawn(obj);
      //设置photon昵称
      PhotonNetwork.NickName =  (string)obj;
      Init();
   }

   private void Update()
   {
      if (Input.GetKeyDown(KeyCode.Return))
      {
         UIEvent.ToMain();
      }
   }
}

  • 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

游戏控制类

using Game;
using Game.bean;
using Game.Interface;
using Photon.Pun;

//游戏控制类。负责所有游戏逻辑总控制
//单例,待实现
public class GameController: SingleTonObj<GameController>
{
    private MainPageInfo _mainPageInfoCache;
    private GameController(){}
    
    //具体的游戏逻辑控制,按功能分
    
    //UI控制
    private IUIController _uiController;
    //登录管理
    private ILoginManager _loginManager;
    //玩家数据
    private PlayerInfo _playerInfo;
    //地图
    private IMapManager _mapManager;
    //网络框架
    private IPhotonWrapper _photonWrapper;

    private bool init = false;

    /// <summary>
    /// 初始化
    /// </summary>
    public void Init()
    {
        if (init)
        {
            return;
        }

        init = true;
        InitObj();
        BindUIEvent();
    }

    /// <summary>
    /// 初始化各个逻辑对象的具体类
    /// </summary>
    private void InitObj()
    {
        _uiController=new UIController();
        //_loginManager=new LoginManager();
        _loginManager = new FakeLoginManager();
        _mapManager= new TestMapManager();
        _photonWrapper=new TestPhotonWrapper();
        _playerInfo=new PlayerInfo();
    }

    private void BindUIEvent()
    {
        UIEvent.LoginClick += Login;
        UIEvent.ToMain += ToMain;
        UIEvent.StoreClick += Store;
        UIEvent.SettingClick += Setting;
        UIEvent.MapClick += MapDetail;
        UIEvent.LobbyClick += Lobby;
        UIEvent.QuickStartClick += QuickStart;
        UIEvent.HeroChange += HeroChange;
        UIEvent.GameStart += GameStart;
    }

    private void ToMain()
    {
        _uiController.ShowMain(_mainPageInfoCache);
    }

    private void GameStart(MapInfo mapInfo)
    {
        //游戏开始,根据地图配置,跳到各自的场景
    }

    private void QuickStart()
    {
        _photonWrapper.RandomJoin((result) =>
        {
            if (result)
            {
                _uiController.ShowRoomInfo();
            }
            else
            {
                _photonWrapper.CreateRoom();
            }
        });
    }

    private void Lobby()
    {
        _uiController.ShowLobby();
    }

    private void MapDetail(MapInfo obj)
    {
        _uiController.ShowMapDetail();
    }

    private void Setting()
    {
        _uiController.ShowSetting();
    }

    private void Store()
    {
        _uiController.ShowStore();
    }

    private void HeroChange(HeroInfo heroInfo)
    {
        _playerInfo.chooseHero = heroInfo;
    }

    private void Login(string name, string pwd)
    {
        _loginManager.Login(name,pwd, (loginResult) =>
        {
            if (loginResult.suc)
            {
                _mainPageInfoCache = new MainPageInfo();
                _mainPageInfoCache.userInfo = loginResult.userInfo;
                
                PlayerInfo.Instance.Init();
                PlayerInfo.Instance._userInfo = loginResult.userInfo;
                _mainPageInfoCache.maps = _mapManager.GetAllMap();
                _uiController.ShowLoginSuc(_mainPageInfoCache.userInfo.username);
            }
            else
            {
                _uiController.ShowLoginError();
            }
        });
    }

    /// <summary>
    /// 游戏入口,游戏启动的时候调用
    /// </summary>
    public void Entrance()
    {
        if (PlayerInfo.Instance._userInfo != null)
        {
            _mainPageInfoCache = new MainPageInfo();
            _mainPageInfoCache.userInfo = PlayerInfo.Instance._userInfo;
            _mainPageInfoCache.maps = _mapManager.GetAllMap();
            _uiController.ShowMain(_mainPageInfoCache);
        }else{
            _uiController.ShowLogin();
            PhotonNetwork.ConnectUsingSettings();
            PhotonNetwork.AutomaticallySyncScene = true;
        }
    }
}
  • 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
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157

登录类实例

using System;
using Game.bean;
using Game.Interface;
using Mono.Data.Sqlite;
using UnityEngine;


namespace Game
{
    /// <summary>
    /// 登录实现实例
    /// </summary>
    public class LoginManager:ILoginManager
    {
        private IDataBaseManager _dataBaseManager;
        public LoginManager()
        {
            _dataBaseManager = DataBaseManager.Instance;
        }
        public void Login(string name, string pwd, Action<LoginResult> callBack)
        {
            LoginResult result =new LoginResult();
            //查数据库
            UserInfo userInfo = _dataBaseManager.GetUserInfo(name, pwd);
            //查到了
            bool check = userInfo!=null;
            //且状态为未登录
            if(check){
                result.suc = true;
                result.userInfo = userInfo;
                callBack(result);
            }else{
                //没查到 或者账号已登录
                result.suc = false;
                callBack(result);
            }
        }

    }
}
  • 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

登录结果类

namespace Game.bean
{
    /// <summary>
    /// 登录的结果
    /// </summary>
    public class LoginResult
    {
        public bool suc;
        public UserInfo userInfo;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/93368
推荐阅读
相关标签
  

闽ICP备14008679号