如果我替换数组中对类实例的唯一引用,它会破坏原始实例吗



我正在尝试创建一个基于网格的映射,方法是实例化与每个瓦片关联的类,并将它们存储在一个数组中。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;
}
}
}
}

简而言之,是的,它将被销毁,而不需要您采取其他行动。最后

更长的答案是,实例,或者更具体地说,您引用的对象的内存地址,将可用于垃圾收集。我不知道废弃的内存需要多长时间才能被标记为集合。

我知道,如果你有意将对象设置为null,你可以手动调用垃圾收集器来立即清理它。但是不要这样做,因为您只能调用完整的集合,而不能调用此特定对象上的集中集合。

作为特定情况之外的一般注意事项,如果您有一个对象使用了其他资源,并且您希望立即释放这些资源,例如web连接或文件锁,则应该实现IDisposable。在Dispose()方法中,您将清除所有这些引用。然后,与其让该对象超出范围,不如调用它的dispose方法来立即清理这些资源。否则,它们将保持打开状态,直到垃圾回收按自己的时间表进行。

最新更新