最近,由于开发需要数据存储服务,就跑去Bmob看看,不看不要紧,发现自己以前创建的应用的数据存储服务居然变成非永久的了,只有一年的免费时间,而且还过期了。这对于我将要开发的软件时很不友好的;因此,我就只能去找与Bmob同类型的后端云服务,就是我接下来要说的leanclound。
需求分析:
1.注册登录功能
2.存储游戏数据
数据包含金币数量、钻石数量和背包道具信息,由于leancloud中不能自己设置主键,为了保证每个用户在数据表中只用唯一一条数据,所以每个用户需要在注册完成后,立即往数据表添加添加一条初始数据而且只能添加一次;
3.排行榜
记录并上传所有用户历史最佳成绩,排行显示
功能实现:
1.注册登录leanclound,新建应用
2.创建class,名字为Gamedate,添加行username(string)、diamond(string)、playeritemsmsg(any),playeritemsmsg是用于存储玩家拥有的道具信息的。
3.下载SDK,由于我们只需要存储功能,因此选择下载LeanCloud-SDK-Storage-Unity.ZIP就行了,将解压好的Plugins文件夹直接放置Unity里面就行。
4.创建脚本,添加引用,并且在Awake中添加以下代码:
private void Awake()
{
LCApplication.Initialize("你的AppID", "你的AppKey", "你的MasterKey");
}
这里面的在 AppID这设置里面
1.注册功能
private void LeanCloundSign(string username, string password)
{
if (username == string.Empty || password == string.Empty)
{
return;
}
else
{
LCUser user = new LCUser();
user["username"] = username;
user["password"] = password;
user.SignUp().ContinueWith(t =>
{
if (t.Exception != null)
{
Debug.Log("用户名已存在");
}
else
{
Debug.Log("注册成功");
}
});
}
}
2.登录功能
private void LeanCloundLogin(string username, string password)
{
var res = LCUser.Login(username, password);
res.ContinueWith(e =>
{
if (e.Exception!=null)
{
Debug.Log("登录失败");
}
else
{
Debug.Log("登录成功");
}
});
}
3.添加玩家初始数据至云数据库,由于我们游戏过程中主要是数据的更新,因此,我们需要在注册完成后立即添加一条初始的数据。
private void AddPlayerData(string username)
{
Player player = new Player();
string json = JsonUtility.ToJson(player);
LCObject lc = new LCObject("Gamedate");
lc["username"] = username;
lc["diamond"] = 10;
lc["playeritemsmsg"] = json;
lc.Save().ContinueWith(e =>
{
if (e.Exception != null)
{
Debug.Log(e.Exception);
}
else
{
Debug.Log("上传初始装备数据成功");
}
});
}
4.获取玩家道具信息,在登录完成后,我们就从云数据库拉取一次玩家信息,并赋值给临时的对象来供我们调用,在玩家道具信息发生变更的时候,我们只需要直接更新这个对象,并且将这个更新好的对象传给云端数据库,就可以实现数据同步了。
private void GetPalyerData(string username)
{
LCQuery<LCObject> query = new LCQuery<LCObject>("Gamedate");
query.WhereEqualTo("username", username);
query.First().ContinueWith(e =>
{
if (e.Exception != null)
{
Debug.Log(e.Exception.ToString());
}
else
{
var res = e.Result;
JObject json = JObject.Parse(res.ToString());
player = JsonUtility.FromJson<Player>(json["playeritemsmsg"].ToString());
foreach (var item in player.ItemMsg)
{
Debug.Log("道具序号:" + item.id + " 拥有数量:" + item.num);
}
}
});
}
5.更新本地和服务器数据
public void UpdatePlayerItemsMsg(int itemid,int count )
{
//更新本地玩家数据
var item = player.ItemMsg.Where(it => it.id == itemid).FirstOrDefault();
if (item != null)
{
if (count < 0&&item.num<-count)//不允许透支
{
return;
}
item.num += count;
if (item.num==0)
{
player.ItemMsg.Remove(item);
}
}
else
{
if (count>0)
{
player.ItemMsg.Add(new PlayItemMsg { id =itemid, num= count });
}
}
foreach (var it in player.ItemMsg)
{
Debug.Log("道具序号:" + it.id + " 拥有数量:" + it.num);
}
//上传至云数据库
LCObject lc = LCObject.CreateWithoutData("Gamedate", playerobjectid);
lc["playeritemsmsg"] = player;
lc.Save();
}
6.整合后的脚本大概是这样
using LC.Newtonsoft.Json.Linq;
using LeanCloud;
using LeanCloud.Storage;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class Login : MonoBehaviour
{
/// <summary>
/// 是否登录成功
/// </summary>
public static bool isLogin;
/// <summary>
/// 登录的账号
/// </summary>
public static LCUser _User;
/// <summary>
/// 玩家信息
/// </summary>
public static Player player;
/// <summary>
/// 玩家数据id
/// </summary>
public static string playerobjectid;
public InputField user;//账号
public InputField pass;//密码
public Button sigin;//注册/登录
public Button tologin;//前往登录
private bool isLogining;
private void Awake()
{
LCApplication.Initialize("*******", "******", "*******");
sigin.onClick.AddListener(()=> {
if (isLogining)
{
LeanCloundLogin(user.text,pass.text);
Debug.Log("登录");
}
else
{
LeanCloundSign(user.text,pass.text);
Debug.Log("注册");
}
});
tologin.onClick.AddListener(() =>
{
isLogining = true;
sigin.GetComponentInChildren<Text>().text = "登录";
tologin.gameObject.SetActive(false);
});
}
/// <summary>
/// 注册账号
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
private void LeanCloundSign(string username, string password)
{
if (username == string.Empty || password == string.Empty)
{
return;
}
else
{
LCUser user = new LCUser();
user["username"] = username;
user["password"] = password;
user.SignUp().ContinueWith(t =>
{
if (t.Exception != null)
{
Debug.Log("用户名已存在");///
}
else
{
Debug.Log("注册成功");
//添加玩家初始数据至数据库
AddPlayerData(username);
}
});
}
}
/// <summary>
/// 登录账号
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
private void LeanCloundLogin(string username, string password)
{
var res = LCUser.Login(username, password);
res.ContinueWith(e =>
{
if (e.Exception!=null)
{
Debug.Log("登录失败");
}
else
{
isLogin = true;
_User = e.Result;
GetPalyerData(e.Result.Username);
Debug.Log("登录成功");
}
});
}
/// <summary>
/// 添加玩家初始数据至云数据库
/// </summary>
/// <param name="username"></param>
private void AddPlayerData(string username)
{
Player player = new Player();
string json = JsonUtility.ToJson(player);
LCObject lc = new LCObject("Gamedate");
lc["username"] = username;
lc["diamond"] = 10;
lc["playeritemsmsg"] = json;
lc.Save().ContinueWith(e =>
{
if (e.Exception != null)
{
Debug.Log(e.Exception);
}
else
{
Debug.Log("上传初始装备数据成功");
}
});
}
/// <summary>
/// 获取玩家装备信息
/// </summary>
/// <param name="username"></param>
private void GetPalyerData(string username)
{
LCQuery<LCObject> query = new LCQuery<LCObject>("Gamedate");
query.WhereEqualTo("username", username);
query.First().ContinueWith(e =>
{
if (e.Exception != null)
{
Debug.Log(e.Exception.ToString());
}
else
{
var res = e.Result;
JObject json = JObject.Parse(res.ToString());
player = JsonUtility.FromJson<Player>(json["playeritemsmsg"].ToString());
foreach (var item in player.ItemMsg)
{
Debug.Log("道具序号:" + item.id + " 拥有数量:" + item.num);
}
playerobjectid = json["objectId"].ToString();
}
});
}
/// <summary>
/// 更新本地和服务器数据
/// </summary>
/// <param name="itemid"></param>
/// <param name="count"></param>
public void UpdatePlayerItemsMsg(int itemid,int count )
{
//更新本地玩家数据
var item = player.ItemMsg.Where(it => it.id == itemid).FirstOrDefault();
if (item != null)
{
if (count < 0&&item.num<-count)//不允许透支
{
return;
}
item.num += count;
if (item.num==0)
{
player.ItemMsg.Remove(item);
}
}
else
{
if (count>0)
{
player.ItemMsg.Add(new PlayItemMsg { id =itemid, num= count });
}
}
foreach (var it in player.ItemMsg)
{
Debug.Log("道具序号:" + it.id + " 拥有数量:" + it.num);
}
//上传至云数据库
LCObject lc = LCObject.CreateWithoutData("Gamedate", playerobjectid);
lc["playeritemsmsg"] = player;
lc.Save();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int id = Random.Range(1, 15);
int num = Random.Range(-5, 6);
//随机增加或减少道具序号为id的数量num
UpdatePlayerItemsMsg(id, num);
}
}
}
[System.Serializable]
public class Player
{
public string name;
public List<PlayItemMsg> ItemMsg;
public Player()//初始信息
{
name = "法外狂徒";
ItemMsg = new List<PlayItemMsg>() {
new PlayItemMsg() { id = 1, num = 1 },
new PlayItemMsg() { id = 2, num = 1 },
new PlayItemMsg() { id = 27, num = 1 },
new PlayItemMsg() { id = 3, num = 10 },
new PlayItemMsg() { id = 4, num = 20 }
};
}
}
//玩家拥有装备信息
[System.Serializable]
public class PlayItemMsg
{
public int id;
public int num;
}
运行结果:
改变道具数量:
文章来源:https://www.toymoban.com/news/detail-422985.html
至此,与云端数据库的通讯就算是完成了,接下来制作一个背包让道具信息更直观的显示出来了,还有就是排行榜的实现,以及AB包的制作、上传、下载和读取等,由于篇幅问题,这些将在下篇文章中介绍。文章来源地址https://www.toymoban.com/news/detail-422985.html
到了这里,关于Unity使用leancloud开发弱数据联网游戏(注册、登录和云端数据存读)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!