【问题标题】:How to store references of generated objects如何存储生成对象的引用
【发布时间】:2014-12-18 11:55:08
【问题描述】:

在我的代码中,我使用 Instantiate 生成了一个对象网格,但我不知道如何通过它们的坐标来保持对每个对象的引用(我依靠 int 坐标来保持简单)。起初我查看了 GameObject[,] 但为此我需要知道我的“地图”将变成的最大尺寸,并且我没有该信息,因为它是无限的,因为它是随着玩家移动而生成的。我发现关于 GameObject[,] 的另一个限制是我不能存储负索引,因此我无法在其中存储 x 和 y 值。

你建议我用什么?

谢谢。

【问题讨论】:

  • 你看过分块吗?您可以拥有一个 GameObject[,] 的块,例如 20x20 对象,并在您四处走动时加载和卸载这些块......

标签: c# unity3d


【解决方案1】:

你会有多稀疏?

如果你有很多差距,那么像下面这样的东西会很好用:

public struct GameObjectCoordinate : IEquatable<GameObjectCoordinate>
{
    public int X { get; set; }
    public int Y { get; set; }
    public bool Equals(GameObjectCoordinate other)
    {
        return X == other.X && Y == other.Y;
    }
    public override bool Equals(object obj)
    {
        return obj is GameObjectCoordinate && Equals((GameObjectCoordinate)obj);
    }
    public override int GetHashCode()
    {
        /* There's a speed advantage in something simple like
        unchecked
        {
            return (X << 16 | X >> 16) ^ Y; 
        }
        and a distribution advantage in the code here. It can be worth
        trying both, but be aware that the code commented out here is better
        at small well-spread key values, and that below at large numbers of
        values especially if many are similar, so do any testing with real
        values your application will deal with.
        */  
        unchecked
        {
            ulong c = 0xDEADBEEFDEADBEEF + ((ulong)X << 32) + (ulong)Y;
            ulong d = 0xE2ADBEEFDEADBEEF ^ c;
            ulong a = d += c = c << 15 | c >> -15;
            ulong b = a += d = d << 52 | d >> -52;
            c ^= b += a = a << 26 | a >> -26;
            d ^= c += b = b << 51 | b >> -51;
            a ^= d += c = c << 28 | c >> -28;
            b ^= a += d = d << 9 | d >> -9;
            c ^= b += a = a << 47 | a >> -47;
            d ^= c += b << 54 | b >> -54;
            a ^= d += c << 32 | c >> 32;
            a += d << 25 | d >> -25;
            return (int)(a >> 1);
        }
    }
    Dictionary<GameObjectCoordinate, GameObject> gameObjects = new Dictionary<GameObjectCoordinate, GameObject>();

如果您几乎在每个位置都有一个对象,那么存储数组块,并使用与上述类似的代码来存储块可能会更好。

【讨论】:

    【解决方案2】:

    如果我理解正确,您有一张未知维度的稀疏地图。在这种情况下,使用像 k-d 树这样的树。所有操作都比直接在表中查找更复杂,但使用的空间更少。它还将允许像(-1, -3) 这样的负仓位。 See Wikipedia for details

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2013-12-27
      • 2012-06-11
      • 1970-01-01
      • 2019-07-03
      • 2023-03-22
      相关资源
      最近更新 更多