【发布时间】:2020-12-09 19:59:24
【问题描述】:
我有与Iterating through DataSnapShot.Children stops the execution of code (Unity, Firebase) 类似的问题 这个问题的解决方案也帮助我让我的代码正常工作。但是,我还想调用一个函数,该函数在 for 循环的每次迭代中创建一个新的 GameObject。如果函数仅包含“Debug.Log”语句,for 循环似乎在每次迭代时都会调用 callForEachElement() 函数。一旦我尝试在函数内部实例化一个对象,for 循环就会在第一次调用后停止并且不会实例化该对象。在下面的代码中调用了 Debug.Log("Before instantiation") 并且从不调用 Debug.Log("After instantiation")。如果我想这样做,谁能解释为什么这不起作用以及为什么循环只运行一次?
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");
}
【问题讨论】:
-
GameObject obj = Instantiate(prefab) as GameObject; -
是的,正确的。看起来上面的行 ->
Debug.Log("Before instantiation");是最后一个被执行的行。