unity实时保存对象的位姿,重新运行程序时用最后保存的数据给物体赋值
using UnityEngine;
using System.IO;
// using System.Xml.Serialization;
public class SaveCoordinates : MonoBehaviour
{
public GameObject MainObject;
//读取坐标
private float x;
private float y;
private float z;
private Quaternion quaternion;
private void Start()
{
//D:\BUFFER\Unity\DLLProject01\Assets\Plugins
string[] lines = File.ReadAllLines("Assets\\Plugins\\coordinates.txt");
for (int i = 1; i < lines.Length; i++)
{
string[] parts = lines[i].Split('=');
string variable = parts[0].Trim();
string value = parts[1].Trim();
//print(variable + "===" + value);
if (variable == "x")
{
x = float.Parse(value);
}
else if (variable == "y")
{
y = float.Parse(value);
}
else if (variable == "z")
{
z = float.Parse(value);
}
else if (variable == "quax")
{
quaternion.x = float.Parse(value);
}
else if (variable == "quay")
{
quaternion.y = float.Parse(value);
}
else if (variable == "quaz")
{
quaternion.z = float.Parse(value);
}
else if (variable == "quaw")
{
quaternion.w = float.Parse(value);
}
}
MainObject.transform.position = new Vector3(x, y, z);
MainObject.transform.rotation = quaternion;
}
void Update()
{
// 获取 MainObject 的位置坐标
float quax = -MainObject.transform.localRotation.x;
float quay = MainObject.transform.localRotation.y;
float quaz = -MainObject.transform.localRotation.z;
float quaw = MainObject.transform.localRotation.w;
float x = MainObject.transform.position.x;
float y = -MainObject.transform.position.y;
float z = MainObject.transform.position.z;
// 打开文件,以写入模式写入文本内容
using (var file = System.IO.File.CreateText("Assets\\Plugins\\coordinates.txt"))
{
// 将三个坐标值以空格分隔,并写入文件
file.Write("[PositionRotation]" + "\n");
file.Write("x=" + x + "\n");
file.Write("y=" + y + "\n");
file.Write("z=" + z + "\n");
file.Write("quax=" + quax + "\n");
file.Write("quay=" + quay + "\n");
file.Write("quaz=" + quaz + "\n");
file.Write("quaw=" + quaw + "\n");
}
}
}
txt文件
[PositionRotation]
x=0
y=3.3
z=0.16
quax=0
quay=0
quaz=0
quaw=1