存档
思路:
玩家的位置信息和角度信息全都用string保存,x,y,z之间用"_"分开,等到先要读数据时使用Split()切割字符串获取数据。
怪物数据在保存时每个Key后面加上自己的ID值(这里图方便就用for循环里的"i"代替了)。
等到取数据时就可以找到各自的值。
public void save()
{
//1、保存玩家信息
PlayerController controller = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
Vector3 pos = controller.transform.position;
Vector3 rot = controller.transform.rotation.eulerAngles;
string str = pos.x + "_" + pos.y + "_" + pos.z;
PlayerPrefs.SetString("Player_Position", str);
str = rot.x + "_" + rot.y + "_" + rot.z;
PlayerPrefs.SetString("Player_Rotation", str);
//2、保存怪物的信息
GameObject[] objs= GameObject.FindGameObjectsWithTag("Monster");
PlayerPrefs.SetInt("MonsterCount", objs.Length);
for (int i = 0; i < objs.Length; i++)
{
pos = objs[i].transform.position;
rot = objs[i].transform.rotation.eulerAngles;
str = pos.x + "_" + pos.y + "_" + pos.z;
PlayerPrefs.SetString("Monster_Position"+i, str);
str = rot.x + "_" + rot.y + "_" + rot.z;
PlayerPrefs.SetString("Monster_Rotation"+i, str);
}
PlayerPrefs.Save();
}
读档
切割Key对应字符串数据获取对应的Position和Rotation
public void load()
{
GameObject goPlayer = null;
string strPos = "";
string strRot = "";
string[] msg = null;
float x = 0f;
float y = 0f;
float z = 0f;
//读取玩家信息
strPos = PlayerPrefs.GetString("Player_Position");
msg = strPos.Split('_');
x = float.Parse(msg[0]);
y = float.Parse(msg[1]);
z = float.Parse(msg[2]);
goPlayer = Instantiate<GameObject>(prefabPlayer);
goPlayer.transform.position = new Vector3(x, y, z);
strRot = PlayerPrefs.GetString("Player_Rotation");
msg = strRot.Split('_');
x = float.Parse(msg[0]);
y = float.Parse(msg[1]);
z = float.Parse(msg[2]);
goPlayer.transform.rotation = Quaternion.Euler(new Vector3(x, y, z));
//读取怪兽信息
int count = PlayerPrefs.GetInt("MonsterCount");
for (int i = 0; i < count; i++)
{
GameObject goMonster = Instantiate<GameObject>(prefabMonster);
strPos = PlayerPrefs.GetString("Monster_Position" + i);
print("strPos=" + strPos);
if (!string.IsNullOrEmpty(strPos))
{
msg = strPos.Split('_');
x = float.Parse(msg[0]);
y = float.Parse(msg[1]);
z = float.Parse(msg[2]);
goMonster.transform.position = new Vector3(x, y, z);
}
strRot = PlayerPrefs.GetString("Monster_Rotation" + i);
if (!string.IsNullOrEmpty(strRot))
{
msg = strRot.Split('_');
x = float.Parse(msg[0]);
y = float.Parse(msg[1]);
z = float.Parse(msg[2]);
goMonster.transform.rotation = Quaternion.Euler(new Vector3(x, y, z));
}
}
}