我有一个与迭代DataSnapShot.Children将停止代码的执行(统一,Firebase)类似的问题,这个问题的解决方案也帮助我使我的代码工作。但是,我还想调用一个函数,它在for循环的每一次迭代中都创建一个新的GameObject。如果函数只包含一个“callForEachElement”语句,那么for循环似乎在每次迭代中调用-function()。一旦我试图在函数中实例化一个对象,for循环就会在第一个调用之后停止,而不会实例化该对象。在下面的代码中,调用了Debug.Log(“实例化之前”),而从未调用Debug.Log(“实例化后”)。如果我想这样做的话,谁能解释为什么这个循环不能工作,为什么循环只运行一次呢?
public GameObject prefab;
private void loadEntriesFromServer()
{
FirebaseDatabase.DefaultInstance.GetReference("202012").GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
// Handle the error...
Debug.Log("ERROR IN LOAD ENTRIES");
}
else if (task.IsCanceled)
{
Debug.Log("Task was Cancelled");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
using (var sequenceEnum = snapshot.Children.GetEnumerator())
{
for (int i = 0; i < snapshot.Children.Count(); i++)
{
while (sequenceEnum.MoveNext())
{
try
{
IDictionary dictUser = (IDictionary)sequenceEnum.Current.Value;
Debug.Log("displayName:" + dictUser);
callForEachElement();
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
}
}
}
}
});
void callForEachElement()
{
Debug.Log("Before instantiation");
GameObject obj = Instantiate(prefab) as GameObject;
Debug.Log("After instantiation");
}发布于 2020-12-09 23:46:06
不能保证ContinueWith在主线程上运行,您只能在主线程上安全地运行Instantiate。考虑将实例化循环移到任务之外,或者尝试Firebase扩展ContinueWithOnMainThread,描述为这里。
例如。
FirebaseDatabase.DefaultInstance.GetReference("202012").GetValueAsync().ContinueWithOnMainThread(taskhttps://stackoverflow.com/questions/65224002
复制相似问题