Search code examples
c#dictionaryunity-game-engineserialization

How do I make a serialized dictionary in unity for 3d models?


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

[System.Serializable]
public struct ImageInfo
{
    public Texture texture;
    public int width;
    public int height;
}

public class ImagesData : MonoBehaviour
{
    public ImageInfo[] images;

    public static Vector2 AspectRatio(float width, float height)
    {
        Vector2 scale = Vector2.one;
    }
}

This is the code for making a serialized dictionary for images which are 2D, how to I make it accept 3D models? I want it to be something like what is in the photo.

Serialized Dictionary for interaction modes


Solution

  • This is the code for making a serialized dictionary for images which are 2D

    No it is not. What you show is a serialized array of ImageInfo.

    For what you show in your image you can simply do

    [Serializable]
    public class ModeInfo
    {
        public string Id;
        public GameObject Value;
    }
    
    public class ModelsDataManager : MonoBehaviour
    {
        public ModeInfo[] InteractionModes;
    }
    

    Or if you want it a bit further with supporting some of the dictionary functionalities

    public class ModelsDataManager : MonoBehaviour
    {
        [SerializeField]
        private List<ModeInfo> InteractionModes;
    
        private bool TryGetInfo(string id, out ModeInfo value)
        {
            foreach (var info in InteractionModes)
            {
                if (info.Id == id)
                {
                    value = info;
                    return true;
                }
            }
    
            value = default;
            return false;
            
            // or same thing using Linq (needs "using System.Linq;")
            //value = InteractionModes.FirstOrDefault(info => info.Id == id);
            //return value != null;
        }
        
        public bool TryGetValue(string id, out GameObject value)
        {
            if (!TryGetInfo(id, out var info))
            {
                value = default;
                return false;
            }
    
            // note that just like in normal dictionaries the value can still be "null" though
            value = info.Value;
            return true;
        }
    
        public void AddOrOverwrite(string id, GameObject value)
        {
            if (!TryGetInfo(id, out var info))
            {
                info = new ModeInfo()
                {
                    Id = id
                };
    
                InteractionModes.Add(info);
            }
    
            info.Value = value;
        }
    }
    

    If you really want to go for the entire dictionary functionality including key checks, cheaper value access without iteration etc I would recommend to not implement this from scratch but rather use an existing solution like e.g.