「用户分享」在 Unity 中使用 LeanCloud

原文由 超级大柱子// 发表于→博客

LeanCloud简介

  • 比之前介绍的ApiCloud更合适Native开发者的云端服务器

  • 官网的文档写的非常棒(暂时是我发现同类中最好的的文档)

  • 看这篇文章之前推荐先看看我的另一篇文章:Unity中的回调函数,协程,基于任务的异步模式, 了解TAP如何使用.

  • 这里只做最精简的总结,和列出Unity中的坑

  • 官网:LeanCloud

在Unity中使用LeanCloud

(下载AVOSCloud.Unity.dll)
导入dll到Unity,引用命名空间

using AVOSCloud;

新建一个AVObject,数据格式如下

var gameScore = new AVObject("GameScore")
{
    { "score", 1338 },
    { "playerName", "Peter Burke" },
    { "cheatMode", false },
    { "skills", new List<string> { "FBI", "Agent Leader" } },
};

注册一个新用户

void Singup(){
    var user = new AVUser ();
    user.Username = SystemInfo.deviceUniqueIdentifier;  //唯一识别码
    user.Password = SystemInfo.deviceUniqueIdentifier.Substring(2, 14);
    user["testA"] = "aaa";
    user.SignUpAsync ().ContinueWith (t => {
        if(t.IsFaulted || t.IsCanceled){
            Debug.Log(t.Exception.Message);
        } else {
            Debug.Log(t.Exception.Message);
            string uid = user.ObjectId;
        }
});

登录已有用户

void Login(){
    AVUser.LogInAsync (username, password).ContinueWith (t => {
        if(t.IsFaulted || t.IsCanceled){
            Debug.Log(t.Exception.Message);
        }
        else {
            string str = AVUser.CurrentUser.Get<string>("Username");
            Debug.Log(str);
        }
    });
}

数据常用方法

void Updata(){
    //updata data
    AVObject ao = AVUser.CurrentUser;
    ao["testA"] = "a5";
    //add remove
    ao.Add ("testB", "b1");
    ao.Remove("testA");
    //link focusType 使用链接对象
    AVObject sceneData = new AVObject("GirType");
    sceneData["typeName"] = "class1";
    ao ["SceneData"] = sceneData;
    //Async
    ao.SaveAsync ();
}

链接对象的读取

void LoadFoucsType(){
    //loadd focusType
    AVObject theSceneData = AVUser.CurrentUser.Get<AVObject> ("SceneData");
    Task<AVObject> fetchTask = theSceneData.FetchIfNeededAsync ();
    Debug.Log (theSceneData.Get<string> ("typeName"));
}

需要注意,当从 LeanCloud 上读取某一对象的数据时,默认的 Fetch 方法不会加载与之相关联的对象的字段,只有执行以下代码后,这些关联数据字段(如上例中 theSceneData 的 typeName 字段)才会被实例化。

可能会遇到的坑

  • AVUser.Passward无法被识别,导致无法创建新用户

如果你用的是MonoDevelop而不是VC作为编辑器,恭喜你,你会遇到这个坑,解决方法:
a1.去Mono官网下载最新的Mono + GTK# http://www.monodevelop.com/download/
a2.安装完成之后,在MonoDevelop中设置.Net版本为最新版
a3.MonoDevelop编辑器中还是会提示AVUser.Passward无法被识别,不管它,运行会成功的.

  • Task.Result无法被识别

解决方法:不管它,手动完整输完它,运行会成功的.

你好,我用unity 加入android的蓝牙模块 然后发布成APK 当Task返回结果时会造成线程阻塞问题 从而导致程序直接退出 蓝牙模块实时接收数据的 频率非常高