unity保存运⾏时的操作_[Unity]保存运⾏时对Scene中
GameObject属性的修改
google中原链接已失效,只剩快照了(unity3d-save-your-in-play-transform-modifications),所以写篇⽂章记录⼀下.
很多时候,我们想把运⾏游戏时对场景中物体属性的修改保存下来,但⼀旦停⽌运⾏这些修改就恢复运⾏前的状态了。对于有原Prefab的物体⽐较好办,把运⾏中修改后的物体直接拖回去覆盖原Prefab即可.⽽对只在Scene中存在的GameObject就没法这样做了。这⾥以transform为例总结⼀种解决⽅法.
总体思路就是在运⾏中修改完毕后,save到某⽂件中,然后停⽌运⾏后再读取回来。但过程中⼜牵扯到⼀个问题:如果给transform添加按钮会改变transform的布局,⽽且⽤base.DrawDefaultInspector();或者base.OnInspectorGUI();都并不能画出默认布局的样⼦,⽽是会变成这样:
多出来个W,很难看。所以我们要先解决默认视图布局的问题,⽅法是⽤下⾯提到的DrawABetterInspector()函数来绘制.然后我们添加Save和Load两个按钮并添加相关功能.
代码如下:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(Transform))]
public class TransformEditor : Editor
{
public void DrawABetterInspector(Transform t)
{
// Replicate the standard transform inspector gui
EditorGUIUtility.labelWidth = 25;
EditorGUIUtility.fieldWidth = 50;
EditorGUI.indentLevel = 0;
Vector3 position = EditorGUILayout.Vector3Field("Position", t.localPosition);
Vector3 eulerAngles = EditorGUILayout.Vector3Field("Rotation", t.localEulerAngles);
Vector3 scale = EditorGUILayout.Vector3Field("Scale", t.localScale);
EditorGUIUtility.labelWidth = 0;
EditorGUIUtility.fieldWidth = 0;
if (GUI.changed)
{
Undo.RecordObject(t, "Transform Change");
t.localPosition = FixIfNaN(position);
t.localEulerAngles = FixIfNaN(eulerAngles);
t.localScale = FixIfNaN(scale);
}
getsavefilename}
private Vector3 FixIfNaN(Vector3 v)
{
if (float.IsNaN(v.x))
{
v.x = 0.0f;
}
if (float.IsNaN(v.y))
{
v.y = 0.0f;
}
if (float.IsNaN(v.z))
{
v.z = 0.0f;
}
return v;
}
public override void OnInspectorGUI()
{
Transform t = (Transform)target; DrawABetterInspector(t);
if (GUILayout.Button("Save"))
{
SaveData(t.gameObject);
}
if (GUILayout.Button("Load"))
{
LoadData(t.gameObject);
}
}
string GetInstanceFileName(GameObject baseObject) {
return System.IO.Path.GetTempPath() + baseObject.name + "_" + baseObject.GetInstanceID() + ".";
}
public void SaveData(GameObject baseObject)
{
List saveData = new List();
saveData.Add(this.GetInstanceID().ToString());
saveData.ToString());
saveData.ToString());
saveData.ToString());
saveData.ansform.ToString());
saveData.ansform.ToString());
saveData.ansform.ToString());
saveData.ToString());
saveData.ToString());
saveData.ToString());
System.IO.File.WriteAllLines(GetInstanceFileName(baseObject), saveData.ToArray());
}
public void LoadData(GameObject baseObject)
{
string[] lines = System.IO.File.ReadAllLines(GetInstanceFileName(baseObject));
if (lines.Length > 0)
{
System.Convert.ToSingle(lines[5]), System.Convert.ToSingle(lines[6]));
System.IO.File.Delete(GetInstanceFileName(baseObject));
}
}
}
将以上⽂件保存为TransformEditor.cs并保存到Assets/Editor⽂件夹下即可,修改后的Transform⾯板如下:
创建⼀个Cube,运⾏场景,对其Transform做些修改,点Save保存.然后停⽌场景,Cube恢复修改前的样⼦.此时再点击Load,可以看到保存的修改被加载回来了.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论