c# - Parse.com 查询的主线程问题

标签 c# unity-game-engine parse-platform

我正在尝试在我的 Unity 游戏中使用 parse.com 服务。我的问题是根据查询收到的结果实例化对象。

例如,当我运行以下代码时;

var queryCurrent = ParseObject.GetQuery("Levels")
.WhereEqualTo("ItemId", "Character")
.WhereEqualTo("Level", "3");

queryCurrent.FirstAsync().ContinueWith(t =>
{
    Character character = ScriptableObject.CreateInstance<Character>();
});

我收到以下错误;

CreateInstanceFromType can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

这似乎是一个普遍问题,每个人都试图通过使用协程来找到解决方法。优化的解决方案将不胜感激。

提前致谢。

最佳答案

使用协程在主线程上运行。它记录在 Parse 站点上:https://parse.com/docs/unity_guide#tasks-coroutines

编辑:

Unity 提供了用于协作多任务处理的协程概念,允许代码在主线程上运行时交错运行。任务和延续模型大多独立于这种多任务机制,但很容易适应在协程中工作。您的协程可以简单地检查任务的 IsCompleted 属性来了解异步工作是否已完成,从而允许协程从中断处继续。例如,以下协程代码保存一个对象,然后等待查询返回:

public IEnumerator GameOver()
{
    var gameHistory = new ParseObject("GameHistory");
    gameHistory["score"] = score;
    gameHistory["player"] = ParseUser.CurrentUser;

    var saveTask = gameHistory.SaveAsync();
    while (!saveTask.IsCompleted) yield return null;

    // When the coroutine reaches this point, the save will be complete

    var historyQuery = new ParseQuery<ParseObject>("GameHistory")
        .WhereEqualTo("player", ParseUser.CurrentUser)
        .OrderByDescending("createdAt");

    var queryTask = historyQuery.FindAsync();
    while (!queryTask.IsCompleted) yield return null;

    // The task is complete, so we can simply check for its result to get
    // the current player's game history
    var history = queryTask.Result;
}

关于c# - Parse.com 查询的主线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24441501/

相关文章:

ios - 在没有互联网连接的情况下创建 Parse 用户

xcode - 在 Swift 中将 Parse Core 链接到 Apple Watch

c# - 有人可以帮助使用 Dapper ORM 进行批量更新吗?

c# - 我可以在 azure 函数应用程序中包含图像等资源吗?

unity-game-engine - Unity HDRP 地形上的阴影太暗

ios - 如何查询 Parse.com Date 并将其转换为 NSDate/String

C# .NET 相当于 Java Swing Actions

C# - 将 '.txt' 文件保存到项目根目录

unity-game-engine - 如何在NGUI中使用ScrollView中的Button来滚动对象

android - UNITY 3D 的磁铁脚本