Storing index of element in the element

Simple question, not even sure if it belongs here. I’m just trying to decide on a data structure to use for a game where I have a bunch of GameObjects in a grid. I stored them in a dictionary at first because of the fast access, but I ended up needing some kind of 2D array. Ideally I’m looking for something ordered with hashing, or in other words I could call in two ways: ds[ i ][ j ] OR ds.GetValue(key).

Since I’m not a data structure guru and I’m not sure if that’s possible, I thought of storing the array index in a variable in the GameObject, so I could access it quickly. I don’t add or remove GameObjects and once they’re in the array they won’t change the position in the array guaranteed. It’s feels like a cheap trick so if anyone knows a better way please enlighten me.

You might want to look at a C# indexed property. I just discovered this feature and it’s pretty cool.

Here is basically something that basically does exactly what you want:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameObjectGrid
{
    internal struct v2i : System.IEquatable<v2i>
    {
        public int x, y;
    
        public v2i( int _x, int _y)
        {
            x = _x;
            y = _y;
        }

        public bool Equals(v2i v) { return x == v.x && y == v.y;}
    }

    Dictionary<v2i,GameObject> Cells;

    public GameObjectGrid()
    {
        Reset ();
    }

    public void Reset()
    {
        Cells = new Dictionary<v2i, GameObject> ();
    }

    public GameObject this[int x, int y]
    {
        get
        {
            v2i key = new v2i(x,y);
            if (Cells.ContainsKey( key))
            {
                return Cells[key];
            }
            return null;
        }
        set
        {
            v2i key = new v2i(x,y);
            Cells[key] = value;
        }
    }

    public GameObject GetValue( int x, int y)
    {
        return this[x,y];
    }
}

Call Reset to clear it all out, or else you can poke null into individual cells to clean them out too.

I leave it to you to implement a SetValue… :slight_smile:

Here’s a few lines of code to use the above object.

        GameObjectGrid Grid = new GameObjectGrid ();

        Grid [0, 0] = new GameObject ("Yabba dabba doo at 0,0");
        Grid [10, 0] = new GameObject ("Aaah yeah at 10,0");

        Debug.Log (Grid [0, 0]);
        Debug.Log (Grid [0, 1]);    // nothing

        Debug.Log (Grid.GetValue (10, 0));

If you want, you can insert a line in the setter function that moves the actual game objects somewhere in space according to where it is stored, but that might get confusing.

1 Like

Huh, nifty! Thanks so much.

1 Like