Menu
CoddyTech

게임 저장하기

Coddy Unity 여정의 Unity 게임 아키텍처 섹션에 포함된 레슨. 64개 중 31번째.

저장 데이터는 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은 정상적으로 종료할 때 실행되지만, 휴대폰에서는 백그라운드의 게임이 이 함수 없이 종료될 수 있습니다.

challenge icon

챌린지

중급

island.json에 섬을 저장하세요.

  1. IslandSave.cs에서 public Vector3 playerPosition;와 public List<Vector3> flags;를 포함하는 [System.Serializable] 클래스 IslandSave를 작성하세요.
  2. Start()에서 path를 Path.Combine(Application.persistentDataPath, "island.json")으로 설정하세요.
  3. Save()는 transform.position과 flags를 담은 IslandSave를 JSON 형식으로 path에 씁니다.
  4. Start()는 기존 파일을 다시 읽습니다. 위치를 읽고 각 플래그에 대해 PlantFlag를 호출합니다.

플레이를 누르고, 플래그를 심은 다음, 저장을 누르세요. 정지한 뒤 ‘플레이’를 누르면 플래그가 돌아와 있습니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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에 기록합니다
    }
}

Unity 게임 아키텍처의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드