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