0

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;
2
  • 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> Commented Sep 25, 2019 at 18:17
  • You can't have a list of multiple types. You can either have a list of a common base class or common interface. Commented Sep 25, 2019 at 18:17

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I completely forgot about tuples' existence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.