0
votes

I'm trying to make a "Block" class for a side-scrolling cave game in Unity 2D. I'm looking to have a HashMap/Dictionary whose key is and int (the block's ID) and the value is a List of multiple types, say, the block's texture (Tile), display name (string), hardness (int), or relationship with gravity (bool).

I'd like it to work like this, but I know this isn't how C# works.

Dictionary<int, List<Tile, int, string, bool>> blockProperties;
1
Lists in C# have to be of a single type. You either need a class with 3 properties, or a Tuple<T1, T2, T3>ESG
You can't have a list of multiple types. You can either have a list of a common base class or common interface.Rufus L

1 Answers

4
votes

Create a data structure to contain the types:

class BlockDescriptor 
{
    public Tile Tile { get; }
    public int Hardness { get;}
    public string DisplayName { get; }
    public bool HasGravity { get; }

    public BlockDescriptor(Tile tile, int hardness, string name, bool gravity)
    {
        Tile = tile;
        Hardness = hardness;
        DisplayName = name;
        HasGravity = gravity;
    }
}

Then you can store them in a dictionary:

Dictionary<int, BlockDescriptor> blockProperties = new Dictionary<int, BlockDescriptor>();
blockProperties.Add(0, new BlockDescriptor(/* Tile */, 1, "Block A", false);
blockProperties.Add(1, new BlockDescriptor(/* Tile */, 2, "Block B", true); 

Alternatively you could use a tuple:

var blockProperties = new Dictionary<int, (Tile, int, string, bool)>();
blockProperties.Add(0, (/* Tile */, 0, "Block A", false));
blockProperties.Add(1, (/* Tile */, 1, "Block B", true));

I recommend choosing a data structure, because you can implement various interfaces such as IEquatable, IEqualityComparer, to affect the behavior within LINQ queries, containers, etc. Additionally, it provides potential for various introspection properties (e.g. IsUnbreakable, HasTileWithTransparency), or methods (e.g. CalculateHardness)