我正在嘗試基于從 firebase 資料庫加載的變換(特別是位置和旋轉)實體化樹預制件。
這里的問題是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
}
}
}
}
uj5u.com熱心網友回復:
大多數 Unity API 只能在 Unity 主執行緒中執行!
您正在使用ContinueWith(Action<Task>)沒有特定的TaskScheduler
創建一個在目標完成時異步執行的延續。
Task
這并不能保證回呼在主執行緒上被呼叫,所以最近Instantiate它失敗了。
Unity 特有的 Firebase 提供了任務擴展方法ContinueWithOnMainThread
System.Threading.Tasks.Task和System.Threading.Tasks.Task<T>允許在 Unity 的主執行緒上執行延續函式的擴展方法。
你應該在這里使用
reference.Child("Player").Child(scenarioName).GetValueAsync().ContinueWithOnMainThread(task =>
{
....
});
一般來說,請確保您沒有在控制臺中禁用任何日志型別。您應該 afaik 已經看到一個警告,告訴您Instantiate不能在主執行緒之外使用。
uj5u.com熱心網友回復:
最有可能的方法Instantiate(treePrefab, loadTreePosition, loadTreeRotation);拋出例外并阻止進一步的回圈迭代。嘗試結束Instantiate();try .. except 并記錄捕獲的例外
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439970.html
