如何存储生成的对象的引用

时间:2014-12-18 11:55:09

标签: c# unity3d

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

您建议我使用什么?

谢谢。

2 个答案:

答案 0 :(得分:0)

你会有多稀疏?

如果你有很多差距,那么下面的内容就会很好用:

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>();

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

答案 1 :(得分:0)

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