【发布时间】:2018-03-19 11:58:51
【问题描述】:
我正在创建一个工具,帮助我工作室中的艺术家轻松设计他们的 UI,然后让他们能够将 UI 导出给开发人员以在他们的项目中使用。
长话短说,我遵循了这个教程:What is the best way to save game state?
当我在同一个脚本中编写所有内容时,它可以正常工作。
但是,当我打开另一个统一项目来导入数据时,它停止了正常工作。它会读取文件,但是应该实例化的 spawnObject 变量保持为空。
我这里使用的类叫做UIdata,它只有一个游戏对象变量inputObject,这个类和我从另一个项目中导出的完全一样
我不太清楚为什么它不工作,如果它从另一个项目导入某些东西,反序列化可以工作吗?
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System;
public class DataSaver
{
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
public static T loadData<T>(string dataFileName)
{
string tempPath = Application.streamingAssetsPath + "/newUICorrect.txt";
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
else
{
Debug.Log("found file");
}
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
string jsonData = Encoding.ASCII.GetString(jsonByte);
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
}
[System.Serializable]
public class UIData
{
public GameObject inputObject;
}
public class LoadingScript : MonoBehaviour
{
private GameObject objectToSpawn;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
importObject();
}
}
public void importObject()
{
UIData loadedData = new UIData();
loadedData = DataSaver.loadData<UIData>("UI");
objectToSpawn = loadedData.inputObject;
if (loadedData == null)
{
return;
}
print(objectToSpawn);
}
}
【问题讨论】:
-
inputObject变量是一种游戏对象,而您 cannot 序列化游戏对象。您可以在 UIData 类中添加有关附加到 GameObject 的类的信息和相关信息,然后对其进行序列化 -
您对此很确定,因为当我序列化一个对象并在另一个脚本上反序列化它时,我得到了它的工作,但由于某种原因它不适用于另一个项目。更不用说,我在上面发布的示例谈到了序列化我认为的对象的可能性
-
你不能序列化一个游戏对象。
inputObject是一个游戏对象...
标签: class unity3d serialization deserialization loading