게임 저장하기
Coddy Unity 여정의 Unity 게임 아키텍처 섹션에 포함된 레슨. 50개 중 25번째.
저장 게임은 JSON으로 기록되는 하나의 객체입니다. 저장에 필요한 모든 것을 [System.Serializable] 클래스에 넣고, 게임에서 값을 채운 다음, 게임이 종료된 후에도 유지되는 위치에 JsonUtility.ToJson으로 변환한 내용을 씁니다. 이 던전은 층, 골드, 발견한 열쇠를 저장합니다:
[System.Serializable]
public class DungeonSave
{
public int floor;
public int gold;
public List<string> keys;
}using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class Dungeon : MonoBehaviour
{
public int floor = 1;
public int gold;
public List<string> keys = new List<string>();
private string path;
void Start()
{
path = Path.Combine(Application.persistentDataPath, "dungeon.json");
if (File.Exists(path))
{
DungeonSave save = JsonUtility.FromJson<DungeonSave>(File.ReadAllText(path));
floor = save.floor;
gold = save.gold;
keys = save.keys;
}
}
public void Save()
{
DungeonSave save = new DungeonSave();
save.floor = floor;
save.gold = gold;
save.keys = keys;
File.WriteAllText(path, JsonUtility.ToJson(save));
}
}Application.persistentDataPath는 Unity가 모든 플랫폼에서 게임에 제공하는 폴더로, 게임을 종료한 뒤에도 그리고 업데이트 후에도 유지됩니다. Path.Combine은 이 경로와 파일 이름을 플랫폼의 구분자로 연결합니다. File.WriteAllText(path, text)는 파일을 쓰며 기존 파일이 있으면 덮어씁니다. File.Exists는 파일이 있는지 알려 주고, File.ReadAllText는 파일 내용을 다시 읽습니다(이 세 가지 모두 System.IO에 있습니다). 게임 자체 폴더는 읽기 전용일 수 있으므로, 저장 데이터는 persistentDataPath에만 저장해야 합니다. 경로는 Awake 또는 Start에서 만드세요. Unity는 필드 초기화 구문에서 persistentDataPath를 사용할 수 없게 합니다.
저장 클래스에는 저장에 필요한 값만 두고, 게임은 저장할 때 값을 클래스에 복사하고 불러올 때 클래스에서 값을 가져옵니다. 작은 저장 데이터는 파일 대신 PlayerPrefs에 저장할 수 있습니다. PlayerPrefs.SetString("dungeon", json)과 PlayerPrefs.GetString("dungeon")은 같은 JSON을 저장하고 불러옵니다. 체크포인트에 도달했을 때나 저장 버튼을 눌렀을 때처럼 보존할 만한 일이 생기면 저장하세요. 정상적으로 종료할 때는 OnApplicationQuit이 실행되지만, 휴대폰에서는 백그라운드에 있는 게임이 이 콜백 없이 종료될 수 있습니다.
챌린지
중급탐험가는 화살표 키로 섬을 돌아다니고, 스페이스바를 누르면 탐험가가 서 있는 위치에 깃발을 꽂습니다. 섬을 파일 island.json에 저장되는 게임으로 만드세요.
IslandSave.cs에[System.Serializable]클래스IslandSave를 작성하고,playerPosition(Vector3)과flags(List<Vector3>)를 public 필드로 선언합니다.- 저장 버튼이 호출하는
Save()는 탐험가의 위치와 깃발을 JSON으로 변환해Application.persistentDataPath의island.json에 씁니다. Start()에서island.json이 있으면 탐험가를 저장된 위치로 되돌리고, 저장된 깃발을 모두 다시 꽂습니다.PlantFlag를 사용해 깃발이 다음 저장을 위한 목록에도 들어가도록 합니다.
Play를 눌러 깃발을 몇 개 꽂고 Save를 클릭한 다음, Stop을 누르고 다시 Play를 누르세요. 그런 다음 Check를 누르세요.
직접 해보기
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.InputSystem;
public class Explorer : MonoBehaviour
{
public GameObject flagPrefab;
public float speed = 4f;
private List<Vector3> flags = new List<Vector3>();
private InputAction moveAction;
void Start()
{
moveAction = InputSystem.actions.FindAction("Move");
// 여기에서 island.json을 불러옵니다
}
void Update()
{
Vector2 input = moveAction.ReadValue<Vector2>();
transform.Translate(new Vector3(input.x, 0f, input.y) * speed * Time.deltaTime);
if (Keyboard.current.spaceKey.wasPressedThisFrame)
{
PlantFlag(transform.position);
}
}
void PlantFlag(Vector3 position)
{
flags.Add(position);
Instantiate(flagPrefab, new Vector3(position.x, 0.5f, position.z), Quaternion.identity);
}
// Save 버튼을 누르면 이것이 호출됩니다
public void Save()
{
// 플레이어의 위치와 깃발들을 island.json에 기록합니다
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.