我需要2个按钮实现存储和读取12个不在同一父对象下的子物体的局部旋转
时间: 2023-12-14 15:35:44 浏览: 24
好的,你可以尝试以下代码:
```c#
using UnityEngine;
using System.Collections.Generic;
public class RotationSaver : MonoBehaviour
{
// 存储按钮触发的方法
public void SaveRotations()
{
List<Quaternion> rotations = new List<Quaternion>();
// 获取所有需要存储旋转的子物体
Transform[] childTransforms = GetComponentsInChildren<Transform>();
foreach (Transform childTransform in childTransforms)
{
// 只存储不在同一父对象下的子物体的旋转
if (childTransform != transform && childTransform.parent != transform)
{
rotations.Add(childTransform.localRotation);
}
}
// 将旋转数据存储到 PlayerPrefs 中
for (int i = 0; i < rotations.Count; i++)
{
PlayerPrefs.SetFloat("rotation_" + i, rotations[i].x);
PlayerPrefs.SetFloat("rotation_" + i + 1, rotations[i].y);
PlayerPrefs.SetFloat("rotation_" + i + 2, rotations[i].z);
PlayerPrefs.SetFloat("rotation_" + i + 3, rotations[i].w);
}
Debug.Log("Rotations saved.");
}
// 读取按钮触发的方法
public void LoadRotations()
{
List<Quaternion> rotations = new List<Quaternion>();
// 从 PlayerPrefs 中读取旋转数据
for (int i = 0; i < 12; i += 4)
{
float x = PlayerPrefs.GetFloat("rotation_" + i);
float y = PlayerPrefs.GetFloat("rotation_" + (i + 1));
float z = PlayerPrefs.GetFloat("rotation_" + (i + 2));
float w = PlayerPrefs.GetFloat("rotation_" + (i + 3));
Quaternion rotation = new Quaternion(x, y, z, w);
rotations.Add(rotation);
}
// 将读取的旋转数据应用到子物体上
Transform[] childTransforms = GetComponentsInChildren<Transform>();
int index = 0;
foreach (Transform childTransform in childTransforms)
{
if (childTransform != transform && childTransform.parent != transform)
{
childTransform.localRotation = rotations[index];
index++;
}
}
Debug.Log("Rotations loaded.");
}
}
```
你可以将上面的代码添加到一个脚本文件中,然后将脚本文件挂载到一个游戏对象上。然后,你可以在场景中添加两个按钮,分别绑定到 `SaveRotations` 和 `LoadRotations` 方法上。这样,当你点击存储按钮时,脚本将会遍历所有不在同一父对象下的子物体,并将其局部旋转存储到 PlayerPrefs 中。当你点击读取按钮时,脚本将会从 PlayerPrefs 中读取旋转数据,并将其应用到相应的子物体上。