[英]Unity OutOfMemoryException List.Add()
我正在Unity3D(版本4.6.1)中為我的FPS實現A *搜索算法。 目前,我在游戲開始時生成了一定數量的敵人預制件,並附有Pathfinder.cs腳本。 在我的Pathfinder類中,每隔1秒(如果我的目標更改了節點),它將調用AStar.cs中的 FindPath()來查找從其自身到目標的新路徑。 目前,玩家是目標; 因此多個敵人可以找到通往同一地點的道路。
我已經做好了一切,敵人找到了預期的道路。 問題是當我的播放器到處走動一段時間(有時需要幾步,有時甚至更長)時,游戲突然凍結,並且任務管理器中的Unity.exe進程拍攝到大約2GB以上的內存(從〜230MB),並且確實如果我停下了現場,就不要下去。 有時Unity凍結一秒鍾,以在控制台中記錄此錯誤:
OutOfMemoryException: Out of memory
System.Array.Resize[Node] (.Node[]& array, Int32 length, Int32 newSize) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Array.cs:1928)
System.Array.Resize[Node] (.Node[]& array, Int32 newSize) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Array.cs:1912)
System.Collections.Generic.List`1[Node].set_Capacity (Int32 value) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:622)
System.Collections.Generic.List`1[Node].GrowIfNeeded (Int32 newCount) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:100)
System.Collections.Generic.List`1[Node].Add (.Node item) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:91)
AStar.CalculatePath (.Node node) (at Assets/Scripts/AStar.cs:152)
AStar.FindPath (Vector3 startPos, Vector3 endPos) (at Assets/Scripts/AStar.cs:109)
Pathfinder.FindPath () (at Assets/Scripts/Pathfinder.cs:64)
Pathfinder.Update () (at Assets/Scripts/Pathfinder.cs:35)
錯誤指向list.Add(node)上的 AStar.cs腳本:
private static List<Node> CalculatePath(Node node) {
List<Node> list = new List<Node>();
while (node != null) {
list.Add(node); //Error here
node = node.parent;
}
list.Reverse();
return list;
}
我最初有ArrayList,但是它出現了相同的錯誤。
重要:
只有1個敵人時不會發生此錯誤。 僅當場景中有1個以上的敵人進行尋路時,才會發生此錯誤。 我以為這是因為AStar類以及打開和關閉列表都是靜態的,所以我嘗試將其更改為在非靜態上下文中使用,但是仍然發生錯誤。
我已經將AStar,Pathfinder和Node類粘貼到pastebin: http ://pastebin.com/4pQU9Pwc
任何幫助是極大的贊賞! 謝謝。
您似乎在向節點添加節點的某種循環邏輯? 在添加列表之前,您是否嘗試過檢查列表是否包含節點?
while (node != null) {
if (!list.Contains(node)) {
list.Add(node);
node = node.parent;
}
else {
break;
}
}
感謝@Altra Viator查找問題的原因,但是最終路徑仍然產生奇怪的結果。 我將CalculatePath方法更改為包括一個起始節點(當前節點為敵人),並添加了一個簡單的檢查方法:
if(node == start) {
break;
}
該方法現在如下所示:
private static List<Node> CalculatePath(Node node, Node start) {
//Retrace the path back through each of the goal nodes parents (to the start node)
List<Node> list = new List<Node>();
while (node != null) {
if (!list.Contains(node)) {
list.Add(node);
if(node == start) {
break;
}
node = node.parent;
}
else {
break;
}
}
list.Reverse();
return list;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.