在SaveTransform方法中,我将所有更改保存到硬盘:
PlayerPrefs.Save();
但是当在LoadTransform方法中使用断点时,我看到父级为null。
loadedTransforms[i].parent = savedTransforms[i].parent;
savedTransforms [i] .parent为空。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.SceneManagement;
public static class TransformSaver
{
[System.Serializable]
public class TransformInfo
{
public string sceneName;
public string name;
public Transform parent;
public Vector3 pos;
public Quaternion rot;
public Vector3 scale;
}
//Save Transform
public static void SaveTransform(Transform[] tranformToSave)
{
TransformInfo[] trnfrm = new TransformInfo[tranformToSave.Length];
for (int i = 0; i < trnfrm.Length; i++)
{
trnfrm[i] = new TransformInfo();
trnfrm[i].sceneName = tranformToSave[i].gameObject.scene.name;
trnfrm[i].name = tranformToSave[i].name;
trnfrm[i].parent = tranformToSave[i].parent;
trnfrm[i].pos = tranformToSave[i].localPosition;
trnfrm[i].rot = tranformToSave[i].localRotation;
trnfrm[i].scale = tranformToSave[i].localScale;
}
string jsonTransform = JsonHelper.ToJson(trnfrm, true);
PlayerPrefs.SetString("transform", jsonTransform);
PlayerPrefs.Save();
}
//Load Transform
public static Transform[] LoadTransform()
{
string jsonTransform = PlayerPrefs.GetString("transform");
if (jsonTransform == null)
{
return null;
}
TransformInfo[] savedTransforms = JsonHelper.FromJson<TransformInfo>(jsonTransform);
GameObject[] gameObjects = new GameObject[savedTransforms.Length];
Transform[] loadedTransforms = new Transform[savedTransforms.Length];
for (int i = 0; i < gameObjects.Length; i++)
{
SceneManager.SetActiveScene(SceneManager.GetSceneByName(savedTransforms[i].sceneName));
gameObjects[i] = new GameObject();
loadedTransforms[i] = gameObjects[i].transform;
loadedTransforms[i].name = savedTransforms[i].name;
loadedTransforms[i].parent = savedTransforms[i].parent;
loadedTransforms[i].localPosition = savedTransforms[i].pos;
loadedTransforms[i].localRotation = savedTransforms[i].rot;
loadedTransforms[i].localScale = savedTransforms[i].scale;
}
return loadedTransforms;
}
}
这是我使用方法的方式:
private void SaveLoad()
{
if (GUILayout.Button("Save"))
{
var selected = Selection.objects.OfType<GameObject>().ToList();
if (selected.Count > 0)
{
for (var i = selected.Count - 1; i >= 0; --i)
{
var select = selected[i];
transformSelection.Add(select.transform);
}
TransformSaver.SaveTransform(transformSelection.ToArray());
tempSelections = transformSelection;
transformSelection = new List<Transform>();
}
}
if (GUILayout.Button("Load"))
{
TransformSaver.LoadTransform();
}
}
答案 0 :(得分:1)
Transforms
无法序列化(但是您知道,这就是您创建此类的原因)
但是:
public Transform parent;
...
trnfrm[i].parent = tranformToSave[i].parent;
您仍在尝试序列化Transform
!
与其尝试以这种方式序列化转换(子代操作),不如尝试以其他方式序列化?如果某个转换有子,则创建一个TransformInfo
数组,并将该转换的子项填充到其中(父级向下)。
还应注意,PlayerPrefs不适用于此类数据。它以纯文本格式存储,用户可以轻松地自由查找和编辑它,并且尺寸非常有限。