foreach循环只迭代一次?C#Unity3D



我正在尝试基于从firebase数据库加载的转换(特别是位置和旋转(实例化一个树预制。

这里的问题是foreach循环只迭代一次,即使快照中总共有4个子级。孩子们,所以我很困惑为什么它只运行一次。

这是的方法

public void GetTrees()
{
reference.Child("Player").Child(scenarioName).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
foreach (DataSnapshot tree in snapshot.Children)
{
xPos = float.Parse(tree.Child("xPos").Value.ToString());
yPos = float.Parse(tree.Child("yPos").Value.ToString());
zPos = float.Parse(tree.Child("zPos").Value.ToString());
xRot = float.Parse(tree.Child("xRot").Value.ToString());
yRot = float.Parse(tree.Child("yRot").Value.ToString());
zRot = float.Parse(tree.Child("zRot").Value.ToString());
wRot = float.Parse(tree.Child("wRot").Value.ToString());
Vector3 loadTreePosition = new Vector3(xPos, yPos, zPos);
Quaternion loadTreeRotation = new Quaternion(xRot, yRot, zRot, wRot);
//returns the position of Tree 0 (31.63, .03, -38.79)
Debug.Log("Tree Positons " + loadTreePosition); 
//returns the rotation of Tree 0 (0,0,0,1)
Debug.Log("Tree Rotations " + loadTreeRotation);
//returns 4
Debug.Log(snapshot.ChildrenCount);
Instantiate(treePrefab, loadTreePosition, loadTreeRotation);
//THIS DOES NOT RETURN ANYTHING 
Debug.Log(snapshot.ChildrenCount);
}
}
});
}

下面是控制台,其中包含方法中显示的debug.log语句调试日志控制台映像

以下是数据库信息作为json

{
"Player" : {
"test" : {
"Tree 0" : {
"mesh" : "palm-01 Instance",
"wRot" : 1,
"xPos" : 31.629507064819336,
"xRot" : 0,
"yPos" : 0.029083967208862305,
"yRot" : 0,
"zPos" : -38.7875862121582,
"zRot" : 0
},
"Tree 1" : {
"mesh" : "palm-01 Instance",
"wRot" : 1,
"xPos" : 31.059694290161133,
"xRot" : 0,
"yPos" : 0.029083967208862305,
"yRot" : 0,
"zPos" : -40.921390533447266,
"zRot" : 0
},
"Tree 2" : {
"mesh" : "palm-01 Instance",
"wRot" : 1,
"xPos" : 31.059694290161133,
"xRot" : 0,
"yPos" : 0.029083967208862305,
"yRot" : 0,
"zPos" : -40.921390533447266,
"zRot" : 0
},
"Tree 3" : {
"mesh" : "palm-01 Instance",
"wRot" : 1,
"xPos" : 31.46793556213379,
"xRot" : 0,
"yPos" : 0.029083967208862305,
"yRot" : 0,
"zPos" : -43.42497253417969,
"zRot" : 0
}
}
}
}

大部分Unity API只能在Unity主线程中执行!

您使用的ContinueWith(Action<Task>)没有特定的TaskScheduler

创建一个延续,在目标Task完成时异步执行

这不能确保回调是在主线程上调用的,所以最晚在Instantiate时它会失败。

特定于Unity的Firebase提供了任务扩展方法ContinueWithOnMainThread

System.Threading.Tasks.TaskSystem.Threading.Tasks.Task<T>的扩展方法,允许在Unity中的主线程上执行延续函数。

您应该在此处使用

reference.Child("Player").Child(scenarioName).GetValueAsync().ContinueWithOnMainThread(task =>
{
....
});

通常,请确保您没有在控制台中禁用任何日志类型。您应该看到一条警告,告诉您Instantiate不能在主线程之外使用。

最有可能的方法Instantiate(treePrefab, loadTreePosition, loadTreeRotation);抛出异常,从而阻止进一步的循环迭代。尝试将Instantiate();封装为Try。。排除并记录捕获的异常

最新更新