我正在嘗試通過實體化與每個圖塊關聯的類并將它們存盤在陣列中來創建基于網格的地圖。GenerateBattlefieldTiles() 方法只是生成一個通用瓦片的完整地圖,這些地圖將被以后的方法替換。現在我正在研究路徑生成器,并且想知道替換陣列中的實體是否會破壞實體,因為陣列是對所述實體的唯一參考,或者我是否必須在替換之前破壞實體。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BattlefieldManager : MonoBehaviour
{
public int pathWaypointCount;
public List<PathTile> paths;
public BattlefieldTile[,] battlefieldTiles;
public int xSize;
public int ySize;
public int seed;
public enum TileType { Path, Obstacle, Generic, Buildable }
// Start is called before the first frame update
void Start()
{
}
void GenerateBattlefieldTiles()
{
battlefieldTiles = new BattlefieldTile[xSize, ySize];
for (int y = 0; y < battlefieldTiles.GetLength(1); y )
{
for (int x = 0; x < battlefieldTiles.GetLength(0); x )
{
Vector2 tilePosition = new Vector2(x - xSize / 2, ySize / 2 - y);
battlefieldTiles[x, y] = new BattlefieldTile(TileType.Generic, tilePosition, new Vector2(x, y));
}
}
}
void GenerateWaypoints()
{
Random.InitState(seed);
int entryYValue = Random.Range(1, ySize - 1);
int exitYValue = Random.Range(1, ySize - 1);
PathTile entryTile = new PathTile(TileType.Path, new Vector2(-xSize / 2, battlefieldTiles.GetLength(1) / 2 - entryYValue), new Vector2(0, entryYValue));
paths.Add(entryTile);
battlefieldTiles[0, entryYValue] = entryTile;
PathTile exitTile = new PathTile(TileType.Path, new Vector2(xSize / 2, battlefieldTiles.GetLength(1) / 2 - exitYValue), new Vector2(xSize, exitYValue));
battlefieldTiles[xSize, exitYValue] = exitTile;
while (paths.Count < pathWaypointCount)
{
Vector2 newWaypoint = new Vector2(Random.Range(1, xSize - 1), Random.Range(1, ySize - 1));
int i = 0;
foreach (PathTile path in paths)
{
if (newWaypoint == path.arrayRef)
{
return;
}
if (Mathf.Abs(newWaypoint.x - path.arrayRef.x) == 1 && Mathf.Abs(newWaypoint.y - path.arrayRef.y) == 1)
{
i ;
if (i >= 2)
{
return
}
}
PathTile pathTile = new PathTile(TileType.Path, new Vector2(newWaypoint.x - xSize / 2, ySize / 2 - newWaypoint.y), newWaypoint);
paths.Add(pathTile);
battlefieldTiles[Mathf.RoundToInt(newWaypoint.x), Mathf.RoundToInt(newWaypoint.y)] = pathTile;
}
}
}
}
uj5u.com熱心網友回復:
簡而言之,是的,它會被摧毀,因為你沒有采取其他行動。最終。
更長的答案是實體,或者更具體地說,您參考的物件的記憶體地址,將可用于垃圾收集。我不知道廢棄的記憶體需要多長時間才能被標記為收集。
我確實知道,如果您故意將物件設定為 null,您可以手動呼叫垃圾收集器來立即清理它。但是不要這樣做,因為你只能呼叫一個完整的集合,而不是一個專注于這個特定物件的集合。
作為您特定情況之外的一般說明,如果您有一個物件具有它使用的其他資源,并且您希望更快地釋放這些資源,例如 Web 連接或檔案鎖定,您應該實作IDisposable. Dispose()然后,在該方法中,您將清理所有這些參考。然后,您可以呼叫它的 dispose 方法來立即清理這些資源,而不僅僅是讓該物件超出范圍。否則,它們將保持打開狀態,直到垃圾收集按自己的時間表處理它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408549.html
標籤:
上一篇:Unity中的多型性與單一行為
