Unity 場景匯出XML或JSON二進位制並且解析還原場景
場景匯出XML或JSON二進位制並且解析還原場景
首次按自己先找一個Scene或者自己做一個也可以。我就是自己做一個。
然後給Sphere新增一個指令碼(Sphere圍繞著cube運動):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
public GameObject MySphere;
private float speed = 3;
public Vector3[] myPosition;
int index;
// Use this for initialization
void Start () {
index = 0;
}
// Update is called once per frame
void Update () {
MySphere.transform.position = Vector3.MoveTowards(MySphere.transform.position,myPosition[index],speed*Time.deltaTime);
if (MySphere.transform.position==myPosition[index])
{
index++;
}
if (index==4)
{
index = 0;
}
}
}
一個小場景就做好了。
接下在就是把把場景轉換成二進位制的json和xml格式。(不懂的可以看雨鬆的文章,寫的非常詳細和不錯哦)
MyEditor指令碼(放入Editor資料夾):
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using LitJson;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
public class MyEditor : Editor
{
//將所有遊戲場景匯出為XML格式
[MenuItem ("GameObject/ExportXML")]
static void ExportXML ()
{
string filepath = Application.dataPath + @"/StreamingAssets/my.xml";
if(!File.Exists (filepath))
{
File.Delete(filepath);
}
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("gameObjects");
//遍歷所有的遊戲場景
foreach (UnityEditor.EditorBuildSettingsScene S in UnityEditor.EditorBuildSettings.scenes)
{
//當關卡啟用
if (S.enabled)
{
//得到關卡的名稱
string name = S.path;
//開啟這個關卡
EditorApplication.OpenScene(name);
XmlElement scenes = xmlDoc.CreateElement("scenes");
scenes.SetAttribute("name",name);
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.transform.parent == null)
{
XmlElement gameObject = xmlDoc.CreateElement("gameObjects");
gameObject.SetAttribute("name",obj.name);
gameObject.SetAttribute("asset",obj.name + ".prefab");
XmlElement transform = xmlDoc.CreateElement("transform");
XmlElement position = xmlDoc.CreateElement("position");
XmlElement position_x = xmlDoc.CreateElement("x");
position_x.InnerText = obj.transform.position.x+"";
XmlElement position_y = xmlDoc.CreateElement("y");
position_y.InnerText = obj.transform.position.y+"";
XmlElement position_z = xmlDoc.CreateElement("z");
position_z.InnerText = obj.transform.position.z+"";
position.AppendChild(position_x);
position.AppendChild(position_y);
position.AppendChild(position_z);
XmlElement rotation = xmlDoc.CreateElement("rotation");
XmlElement rotation_x = xmlDoc.CreateElement("x");
rotation_x.InnerText = obj.transform.rotation.eulerAngles.x+"";
XmlElement rotation_y = xmlDoc.CreateElement("y");
rotation_y.InnerText = obj.transform.rotation.eulerAngles.y+"";
XmlElement rotation_z = xmlDoc.CreateElement("z");
rotation_z.InnerText = obj.transform.rotation.eulerAngles.z+"";
rotation.AppendChild(rotation_x);
rotation.AppendChild(rotation_y);
rotation.AppendChild(rotation_z);
XmlElement scale = xmlDoc.CreateElement("scale");
XmlElement scale_x = xmlDoc.CreateElement("x");
scale_x.InnerText = obj.transform.localScale.x+"";
XmlElement scale_y = xmlDoc.CreateElement("y");
scale_y.InnerText = obj.transform.localScale.y+"";
XmlElement scale_z = xmlDoc.CreateElement("z");
scale_z.InnerText = obj.transform.localScale.z+"";
scale.AppendChild(scale_x);
scale.AppendChild(scale_y);
scale.AppendChild(scale_z);
transform.AppendChild(position);
transform.AppendChild(rotation);
transform.AppendChild(scale);
gameObject.AppendChild(transform);
scenes.AppendChild(gameObject);
root.AppendChild(scenes);
xmlDoc.AppendChild(root);
xmlDoc.Save(filepath);
}
}
}
}
//重新整理Project檢視, 不然需要手動重新整理哦
AssetDatabase.Refresh();
}
//將所有遊戲場景匯出為JSON格式
[MenuItem ("GameObject/ExportJSON")]
static void ExportJSON ()
{
string filepath = Application.dataPath + @"/StreamingAssets/json.txt";
FileInfo t = new FileInfo(filepath);
if(!File.Exists (filepath))
{
File.Delete(filepath);
}
StreamWriter sw = t.CreateText();
StringBuilder sb = new StringBuilder ();
JsonWriter writer = new JsonWriter (sb);
writer.WriteObjectStart ();
writer.WritePropertyName ("GameObjects");
writer.WriteArrayStart ();
foreach (UnityEditor.EditorBuildSettingsScene S in UnityEditor.EditorBuildSettings.scenes)
{
if (S.enabled)
{
string name = S.path;
EditorApplication.OpenScene(name);
writer.WriteObjectStart();
writer.WritePropertyName("scenes");
writer.WriteArrayStart ();
writer.WriteObjectStart();
writer.WritePropertyName("name");
writer.Write(name);
writer.WritePropertyName("gameObject");
writer.WriteArrayStart ();
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.transform.parent == null)
{
writer.WriteObjectStart();
writer.WritePropertyName("name");
writer.Write(obj.name);
writer.WritePropertyName("position");
writer.WriteArrayStart ();
writer.WriteObjectStart();
writer.WritePropertyName("x");
writer.Write(obj.transform.position.x.ToString("F5"));
writer.WritePropertyName("y");
writer.Write(obj.transform.position.y.ToString("F5"));
writer.WritePropertyName("z");
writer.Write(obj.transform.position.z.ToString("F5"));
writer.WriteObjectEnd();
writer.WriteArrayEnd();
writer.WritePropertyName("rotation");
writer.WriteArrayStart ();
writer.WriteObjectStart();
writer.WritePropertyName("x");
writer.Write(obj.transform.rotation.eulerAngles.x.ToString("F5"));
writer.WritePropertyName("y");
writer.Write(obj.transform.rotation.eulerAngles.y.ToString("F5"));
writer.WritePropertyName("z");
writer.Write(obj.transform.rotation.eulerAngles.z.ToString("F5"));
writer.WriteObjectEnd();
writer.WriteArrayEnd();
writer.WritePropertyName("scale");
writer.WriteArrayStart ();
writer.WriteObjectStart();
writer.WritePropertyName("x");
writer.Write(obj.transform.localScale.x.ToString("F5"));
writer.WritePropertyName("y");
writer.Write(obj.transform.localScale.y.ToString("F5"));
writer.WritePropertyName("z");
writer.Write(obj.transform.localScale.z.ToString("F5"));
writer.WriteObjectEnd();
writer.WriteArrayEnd();
writer.WriteObjectEnd();
}
}
writer.WriteArrayEnd();
writer.WriteObjectEnd();
writer.WriteArrayEnd();
writer.WriteObjectEnd();
}
}
writer.WriteArrayEnd();
writer.WriteObjectEnd ();
sw.WriteLine(sb.ToString());
sw.Close();
sw.Dispose();
AssetDatabase.Refresh();
}
[MenuItem ("GameObject/BINARY")]
static void XMLJSONTOBinary ()
{
string filepath = Application.dataPath + @"/StreamingAssets/binary.txt";
if(File.Exists (filepath))
{
File.Delete(filepath);
}
FileStream fs = new FileStream(filepath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
foreach (UnityEditor.EditorBuildSettingsScene S in UnityEditor.EditorBuildSettings.scenes)
{
if (S.enabled)
{
string name = S.path;
EditorApplication.OpenScene(name);
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.transform.parent == null)
{
bw.Write(name);
bw.Write(obj.name);
short posx = (short)(obj.transform.position.x * 100);
bw.Write(posx);
bw.Write((short)(obj.transform.position.y * 100.0f));
bw.Write((short)(obj.transform.position.z * 100.0f));
bw.Write((short)(obj.transform.rotation.eulerAngles.x * 100.0f));
bw.Write((short)(obj.transform.rotation.eulerAngles.y * 100.0f));
bw.Write((short)(obj.transform.rotation.eulerAngles.z * 100.0f));
bw.Write((short)(obj.transform.localScale.x * 100.0f));
bw.Write((short)(obj.transform.localScale.y * 100.0f));
bw.Write((short)(obj.transform.localScale.z * 100.0f));
}
}
}
}
bw.Flush();
bw.Close();
fs.Close();
}
}
放進去後可以看到:
然後別忘記把場景新增到Buildsetting裡面(需要copy的場景)。
匯出來的檔案放入到:
Xml(指令碼):
using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
using UnityEngine.SceneManagement;
public class XML : MonoBehaviour
{
// Use this for initialization
void Start()
{
//電腦和iphong上的路徑是不一樣的,這裡用標籤判斷一下。
//#if UNITY_EDITOR
string filepath = Application.dataPath + "/StreamingAssets" + "/my.xml";//#elif UNITY_IPHONE
// string filepath = Application.dataPath +"/Raw"+"/my.xml";
//#endif
//如果檔案存在話開始解析。
if (File.Exists(filepath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filepath);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("gameObjects").ChildNodes;
foreach (XmlElement scene in nodeList)
{
//因為我的XML是把所有遊戲物件全部匯出, 所以這裡判斷一下只解析需要的場景中的遊戲物件
//JSON和它的原理類似
if (!scene.GetAttribute("name").Equals("Assets/MySceneOne.unity"))
{
continue;// 獲取屬性 GetAttribute
}
foreach (XmlElement gameObjects in scene.ChildNodes)
{
string asset = "Prefab/" + gameObjects.GetAttribute("name");
Vector3 pos = Vector3.zero;
Vector3 rot = Vector3.zero;
Vector3 sca = Vector3.zero;
foreach (XmlElement transform in gameObjects.ChildNodes)
{
foreach (XmlElement prs in transform.ChildNodes)
{
if (prs.Name == "position")
{
foreach (XmlElement position in prs.ChildNodes)
{
switch (position.Name)
{
case "x":
pos.x = float.Parse(position.InnerText);
break;
case "y":
pos.y = float.Parse(position.InnerText);
break;
case "z":
pos.z = float.Parse(position.InnerText);
break;
}
}
}
else if (prs.Name == "rotation")
{
foreach (XmlElement rotation in prs.ChildNodes)
{
switch (rotation.Name)
{
case "x":
rot.x = float.Parse(rotation.InnerText);
break;
case "y":
rot.y = float.Parse(rotation.InnerText);
break;
case "z":
rot.z = float.Parse(rotation.InnerText);
break;
}
}
}
else if (prs.Name == "scale")
{
foreach (XmlElement scale in prs.ChildNodes)
{
switch (scale.Name)
{
case "x":
sca.x = float.Parse(scale.InnerText);
break;
case "y":
sca.y = float.Parse(scale.InnerText);
break;
case "z":
sca.z = float.Parse(scale.InnerText);
break;
}
}
}
}
//拿到 旋轉 縮放 平移 以後克隆新遊戲物件
GameObject ob = (GameObject)Instantiate(Resources.Load(asset), pos, Quaternion.Euler(rot));
ob.transform.localScale = sca;
}
}
}
}
}
}
Json指令碼:
using UnityEngine;
using System.Collections;
using System.IO;
using LitJson;
using UnityEngine.SceneManagement;
public class JSON : MonoBehaviour
{
// Use this for initialization
void Start()
{
//#if UNITY_EDITOR
string filepath = Application.dataPath + "/StreamingAssets" + "/json.txt";
//#elif UNITY_IPHONE
// string filepath = Application.dataPath +"/Raw"+"/json.txt";
//#endif
StreamReader sr = File.OpenText(filepath);
string strLine = sr.ReadToEnd();
JsonData jd = JsonMapper.ToObject(strLine);
JsonData gameObjectArray = jd["GameObjects"];
int i, j, k;
for (i = 0; i < gameObjectArray.Count; i++)
{
JsonData senseArray = gameObjectArray[i]["scenes"];
for (j = 0; j < senseArray.Count; j++)
{
string sceneName = (string)senseArray[j]["name"];
if (!sceneName.Equals("MySceneOne.unity"))
{
continue;
}
JsonData gameObjects = senseArray[j]["gameObject"];
for (k = 0; k < gameObjects.Count; k++)
{
string objectName = (string)gameObjects[k]["name"];
string asset = "Prefab/" + objectName;
Vector3 pos = Vector3.zero;
Vector3 rot = Vector3.zero;
Vector3 sca = Vector3.zero;
JsonData position = gameObjects[k]["position"];
JsonData rotation = gameObjects[k]["rotation"];
JsonData scale = gameObjects[k]["scale"];
pos.x = float.Parse((string)position[0]["x"]);
pos.y = float.Parse((string)position[0]["y"]);
pos.z = float.Parse((string)position[0]["z"]);
rot.x = float.Parse((string)rotation[0]["x"]);
rot.y = float.Parse((string)rotation[0]["y"]);
rot.z = float.Parse((string)rotation[0]["z"]);
sca.x = float.Parse((string)scale[0]["x"]);
sca.y = float.Parse((string)scale[0]["y"]);
sca.z = float.Parse((string)scale[0]["z"]);
GameObject ob = (GameObject)Instantiate(Resources.Load(asset), pos, Quaternion.Euler(rot));
ob.transform.localScale = sca;
}
}
}
}
}
執行之後就可以載入了。西面效果圖:
最後別忘記把資源Prefab放入到Reasources資料夾裡面: