在Unity中使用C#进行Xml序列化时保留特定小数位的方法参考

序列化方法代码参考:

cs 复制代码
using System.IO;
using System.Xml.Serialization;

public class XmlTool
{
	public static string ToXml<T>(T obj)
	{
		XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
		using var stringWriter = new StringWriter();
		//让xml文档的命名空间为空,文档显得简洁那么一点点。
		XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
		xmlns.Add("","");
		//
		xmlSerializer.Serialize(stringWriter, obj, xmlns);
		return stringWriter.ToString();
	}
	public static T FromXml<T>(string xml)
	{
		XmlSerializer xmlSerializer = new(typeof(T));
		return (T)xmlSerializer.Deserialize(new StringReader(xml));
	}
}

小数位数控制参考:

cs 复制代码
public struct SceneAreaInfo
{
	[XmlAttribute("X")]
	public string strX
	{
		get { return x.ToString("0.##"); }
		set { x = float.Parse(value); }
	}
	[XmlIgnore]
	public float x;//场景区域最左侧坐标

	[XmlAttribute("Y")]
	public string strY
	{
		get { return y.ToString("0.##"); }
		set { y = float.Parse(value); }
	}
	[XmlIgnore]
	public float y;//场景区域最下面坐标

	[XmlAttribute("Width")]
	public string strWidth
	{
		get { return width.ToString("0.##"); }
		set { width = float.Parse(value); }
	}
	[XmlIgnore]
	public float width;//场景区域宽度

	[XmlAttribute("Height")]
	public string strHeight
	{
		get { return height.ToString("0.##"); }
		set { height = float.Parse(value); }
	}
	[XmlIgnore]
	public float height;//场景区域高度

	[XmlIgnore]
	public Vector2 size => new Vector2(width, height);

	public SceneAreaInfo(float x, float y, float width, float height)
	{
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}
	public SceneAreaInfo(Rect rect)
	{
		x = rect.x;
		y = rect.y;
		width = rect.width;
		height = rect.height;
	}
}
相关推荐
武藤一雄1 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
adogai3 小时前
unity mcp接入 实现一句话生成游戏!
游戏·unity·游戏引擎
mxwin4 小时前
Unity Shader 逐像素光照 vs 逐顶点光照性能与画质的权衡策略
unity·游戏引擎·shader·着色器
乱蜂朝王4 小时前
使用 C# 和 ONNX Runtime 部署 PaDiM 异常检测模型
开发语言·c#
CDN3604 小时前
游戏盾导致 Unity/UE 引擎崩溃的主要原因排查?
游戏·unity·游戏引擎
mxwin4 小时前
Unity URP 全局光照 (GI) 完全指南 Lightmap 采样与实时 GI(光照探针、反射探针)的 Shader 集成
unity·游戏引擎·shader·着色器
JosieBook6 小时前
【C#】VS中的 跨线程调试异常:CrossThreadMessagingException
开发语言·c#
追雨潮6 小时前
BGE-M3 多语言向量模型实战:.NET C# 从原理到落地
开发语言·c#·.net
mxwin6 小时前
Unity URP 溶解效果基于噪声纹理与 clip 函数实现物体渐隐渐显
unity·游戏引擎·shader
CheerWWW8 小时前
GameFramework——Download篇
笔记·学习·unity·c#