简体   繁体   English

如何为 3d 模型统一制作序列化字典?

[英]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?这是为二维图像制作序列化字典的代码,如何让它接受 3D 模型? I want it to be something like what is in the photo.我希望它像照片中的那样。

用于交互模式的序列化字典

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 .您显示的是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 eg如果您真的想要 go 的整个字典功能,包括键检查、无需迭代的更便宜的值访问等,我建议不要从头开始实现它,而是使用现有的解决方案,例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM