[英]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;
}
}
这是为二维图像制作序列化字典的代码,如何让它接受 3D 模型? 我希望它像照片中的那样。
这是为二维图像制作序列化字典的代码
不它不是。 您显示的是ImageInfo
的序列化数组。
对于您在图像中显示的内容,您可以简单地做
[Serializable]
public class ModeInfo
{
public string Id;
public GameObject Value;
}
public class ModelsDataManager : MonoBehaviour
{
public ModeInfo[] InteractionModes;
}
或者,如果您希望进一步支持一些字典功能
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;
}
}
如果您真的想要 go 的整个字典功能,包括键检查、无需迭代的更便宜的值访问等,我建议不要从头开始实现它,而是使用现有的解决方案,例如
Unity 自己的一个隐藏在核心 RP 库 Package中(作为依赖项安装,例如 UniversialRenderPipeline 或 HighDefinitionenderPipeline)。
但这是非常基本的,仅用于序列化——没有有用的 Inspector 抽屉
azixMcAze 的 Unity-SerializableDictionary (也可用作package )
有一个很酷的 Inspector 抽屉,甚至可以处理重复的键检查等。
请注意,虽然Odin Inspector不是免费的
或者只是提前 go 并测试其他许多解决方案之一;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.