gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:05:20 25 4
gpt4 key购买 nike

我正尝试在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com