How to create and edit a 2 axis array with Enum on each axis ?

Hello, i want to create some simples 2D arrays, to stores some datas. i would like to get something similar to a realy basic excel file. here is an exemple :

https://i.imgur.com/Pp6HHUL.png

to get something working, i have this :

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

public class TestArray : MonoBehaviour
{    
    enum AnimalEnum : int
    {
        Dog, Donkey, Human, Cat
    }

    enum FoodEnum : int
    {
        Fruit, Meat, Candy,
    }

    [SerializeField]
    public float[,] test = new float[(byte)AnimalEnum.Cat + 1, (byte)FoodEnum.Candy + 1]
        {
     /*            Fruit   Meat    Candy*/
     /*Dog      */{ 7.4f,  8,    9 },
     /*Donkey   */{ 1,     2,    3 },
     /*Human    */{ 1,     1,   30 },
     /*Cat      */{ 1,     2,    3 }
        };


    void GetFoodValue(AnimalEnum animal, FoodEnum food)
    {
        Debug.Log(test[(int)animal, (int)food]);
    }
    void Update()
    {
        if (Input.GetButtonDown("Jump"))
        {
            GetFoodValue(AnimalEnum.Human, FoodEnum.Candy);
        }

    }
}

The base functions work (getings datas for the asked type), but it is not ready readable, and hard to modify (i would like to modify it on a public variable on the inspector, so the designer could set and edit the value easily.

If you want it to be inspector friendly, you have three options:

  • A simple public array of arrays, with no labels. A 2D array will not work to my knowledge. If you want a 2D array in your code, read the next section.
  • A custom inspector for your script, that adds labels to the array of arrays, and maybe changes the layout so it’s easier to read.
  • Better yet, a custom class for your table (a class that contains the array of arrays), with a custom property drawer that does the same thing. This can be reused for multiple scripts.

All of these options don’t changes how your data is serialized. Your class will always store that data in Arrays of Arrays. This is another subject, but basically unity can transform all the public variable (or the ones with the serialized tag) into a text file. This can be used to store prefabs, or to edit an object from the inspector.

If you want a more complex way to use that data in code, like a 2d Array, or a Dictionary of Tuples using both enums as a typesafe key, you need to convert that data to and from your array of arrays, because Dictionaries are not serializable by unity.

To convert that data, you need to implement OnSerialize and OnDeserialize.


Basically, it’s an unintuitive, complex subject that requires a lot of blind testing and using less-than-perfect documentation. I would recommend the first option. Or using one of the many inspector assets that do that for you.