[英]foreach loop iterating only once? C# Unity3D
我正在尝试根据从 firebase 数据库加载的变换(特别是 position 和旋转)实例化一个树预制件。
这里的问题是 foreach 循环只迭代一次,即使在 snapshot.Children 中总共有 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主线程中执行!
您正在使用没有特定TaskScheduler
的ContinueWith(Action<Task>)
创建一个在目标
Task
完成时异步执行的延续。
这不能确保回调在主线程上调用,所以最近在Instantiate
时它失败了。
Firebase Unity专门提供任务扩展方法ContinueWithOnMainThread
System.Threading.Tasks.Task
和System.Threading.Tasks.Task<T>
的扩展方法,允许在 Unity 的主线程上执行延续 function。
你应该在这里使用
reference.Child("Player").Child(scenarioName).GetValueAsync().ContinueWithOnMainThread(task =>
{
....
});
通常确保您没有在控制台中禁用任何日志类型。 你应该 afaik 看到一个警告,告诉你Instantiate
不能在主线程之外使用。
最有可能的方法Instantiate(treePrefab, loadTreePosition, loadTreeRotation);
抛出异常并阻止进一步的循环迭代。 尝试结束Instantiate();
进入 try..except 并记录捕获的异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.