任务是在WebGL中从StreamingAssets中读取xml文件并反序列化。现在结果是:如果Model不在dll中定义,则WebGL中能够反序列化,但如果在dll中定义,则在WebGL中无法反序列化,研究了好几天了,还是无法解决,网上也没有找到类似的,还望大家帮忙QAQ。
下面是我目前的做法:
在Unity中反序列化:
1 using System.Collections; 2 using UnityEngine; 3 using UnityEngine.Networking; 4 using WillConfiguration; 5 using System.IO; 6 using System.Xml.Serialization; 7 8 public class ReadWillXML : MonoBehaviour 9 { 10 public string xmlName; 11 public WillXMLConfiguration willXMLConfiguration; 12 13 // Start is called before the first frame update 14 IEnumerator Start() 15 { 16 UnityWebRequest uwr = UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath, xmlName)); 17 yield return uwr.SendWebRequest(); 18 19 StringReader sr = new StringReader(uwr.downloadHandler.text); 20 sr.ReadLine(); 21 XmlSerializer serializer = new XmlSerializer(typeof(WillXMLConfiguration)); 22 willXMLConfiguration = (WillXMLConfiguration)serializer.Deserialize(sr); 23 24 sr.Close(); 25 Debug.Log("### Number = " + willXMLConfiguration.Number); 26 Debug.Log("### Frontwards = " + willXMLConfiguration.Frontwards); 27 Debug.Log("### Position X = " + willXMLConfiguration.Position.X + " Y = " + willXMLConfiguration.Position.Y); 28 Debug.Log("The End!"); 29 } 30 }
Model层的定义(Build成dll)
1 using System.Xml.Serialization; 2 using System.Runtime.Serialization; 3 4 namespace WillConfiguration 5 { 6 7 [XmlRoot(ElementName = "WillConfiguration"), DataContract(Name = "WillConfiguration")] 8 public class WillXMLConfiguration 9 { 10 [XmlAttribute(AttributeName = "Number"), DataMember(Name = "Number")] 11 public string Number { get; set; } 12 [XmlAttribute(AttributeName = "Frontwards"), DataMember(Name = "Frontwards")] 13 public bool Frontwards { get; set; } 14 [XmlElement(ElementName = "Position"), DataMember(Name = "Position")] 15 public WillXMLPosition Position { get; set; } 16 public WillXMLConfiguration() { } 17 } 18 }
1 using System.Xml.Serialization; 2 using System.Runtime.Serialization; 3 4 namespace WillConfiguration 5 { 6 [XmlRoot(ElementName = "Position"), DataContract(Name = "Position")] 7 public class WillXMLPosition 8 { 9 [XmlAttribute(AttributeName = "X"), DataMember(Name = "X")] 10 public float X { get; set; } 11 [XmlAttribute(AttributeName = "Y"), DataMember(Name = "Y")] 12 public float Y { get; set; } 13 [XmlAttribute(AttributeName = "Z"), DataMember(Name = "Z")] 14 public float Z { get; set; } 15 } 16 }
xml文件(放在StreamingAssets中)
1 <?xml version="1.0" encoding="utf-8"?> 2 <WillConfiguration Number="6" Frontwards="true"> 3 <Position X="1" Y="2" Z="3" /> 4 </WillConfiguration>
------------------------
按照上面的代码,能在unity编辑器中运行,但build成WebGL中就报错,显示
然而在把WillXMLPosition和WillXMLConfiguration两个类加上[Serializable]后,虽然能运行,但得到的都是空值,可以确定的是确实是以字符串的形式读取了xml文件。
最后还是没有解决办法,只能傻瓜式的一一对应了。