게임 내에서 플레이어의 위치와 회전을 저장해야합니다. 이 목적을 위해 바이너리 포맷터와 '저장'과 '로드'버튼 2 개를 사용합니다. 스크립트는 내가 수동으로 기록하고 저장 한 다음 장면을 다시로드하면 공용 Vector3 데이터를 저장합니다. 그러나 플레이어 (큐브 만)는 위치와 회전을 변경하지 않습니다. 이 문제를 해결하기 위해 다음을 추가했습니다.
void FixedUpdate()
{
position = player.transform.position;
rotation = player.transform.rotation;
}
그러나 그것은 도움이되지 않았습니다. 이 작업을 수행하기 위해 2 개의 스크립트를 사용합니다.
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public GameObject player;
public Vector3 position;
public Quaternion rotation;
void FixedUpdate()
{
position = player.transform.position;
rotation = player.transform.rotation;
}
public void Save()
{
SaveLoadManager.SavePlayer(this);
}
public void Load()
{
float[] loadedStats = SaveLoadManager.LoadPlayer();
Vector3 loadedPos = new Vector3(loadedStats[0], loadedStats[1], loadedStats[2]);
Vector3 loadedRot = new Vector3(loadedStats[3], loadedStats[4], loadedStats[5]);
player.transform.position = loadedPos;
player.transform.rotation = Quaternion.Euler(loadedRot);
}
}
SaveLoadManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveLoadManager
{
public static void SavePlayer(Player player)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.save", FileMode.Create);
PlayerData data = new PlayerData(player);
bf.Serialize(stream, data);
stream.Close();
}
public static float[] LoadPlayer()
{
if (File.Exists(Application.persistentDataPath + "/player.save"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.save", FileMode.Open);
PlayerData data = bf.Deserialize(stream) as PlayerData;
stream.Close();
return data.stats;
}
else
{
Debug.LogError("File does not exist.");
return new float[6];
}
}
}
[Serializable]
public class PlayerData
{
public float[] stats;
public PlayerData(Player player)
{
stats = new float[6];
stats[0] = player.position.x;
stats[1] = player.position.y;
stats[2] = player.position.z;
stats[3] = player.rotation.x;
stats[4] = player.rotation.y;
stats[5] = player.rotation.z;
}
}
저는 Save-Load 시스템과 Binary Formatting을 처음 접했기 때문에 도움을 주시길 바랍니다.
미리 감사드립니다!
누락 된 것이 있는지 확실하지 않지만 실제로 Player의 위치를로드 된 값으로 설정하는 Load () 메서드의 아무 곳도 볼 수 없습니다. 대신로드 된 값을 불필요한 변수에 전달한 다음 FixedUpdate ()에서 지속적으로 덮어 쓰는 것처럼 보입니다.
다음과 같이 시도해보십시오.
public void Load()
{
float[] loadedStats = SaveLoadManager.LoadPlayer();
Vector3 loadedPos = new Vector3(loadedStats[0], loadedStats[1], loadedStats[2]);
Vector3 loadedRot = new Vector3(loadedStats[3], loadedStats[4], loadedStats[5]);
player.transform.position = loadedPos ;
player.transform.rotation = Quaternion.Euler(loadedRot);
}
그리고 Player 스크립트에서 위치 및 회전 변수를 제거 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다