개인 프로젝트

대사 관리

hanui1210 2024. 9. 14. 13:42

대사를 게임에 넣으려면, 스토리 데이터를 관리할 구조가 필요합니다. 일반적으로 JSON 파일이나 ScriptableObject를 사용하여 대사 데이터를 저장하고, 이를 Unity에서 불러와 대화를 진행하게 할 수 있습니다. 아래에 두 가지 방법을 설명하겠습니다.

1. JSON 파일을 사용한 대사 관리

JSON 파일은 텍스트 기반의 데이터 파일로, 대화 데이터를 구조적으로 저장하고 불러오는 데 유용합니다.

1) JSON 파일 작성

프로젝트의 Resources 폴더 아래에 dialogue.json 파일을 만들고, 대사 데이터를 추가합니다. 대화를 트리 구조로 작성할 수 있습니다.

예시 JSON 파일 (dialogue.json):

{
    "conversation": [
        {
            "id": 1,
            "speaker": "NPC",
            "text": "안녕하세요! 어떻게 도와드릴까요?",
            "options": [
                {"text": "안녕하세요!", "nextId": 2},
                {"text": "누구세요?", "nextId": 3}
            ]
        },
        {
            "id": 2,
            "speaker": "Player",
            "text": "안녕하세요! 도와드리고 싶습니다.",
            "options": [
                {"text": "다음", "nextId": 4}
            ]
        },
        {
            "id": 3,
            "speaker": "NPC",
            "text": "저는 이 마을의 상인입니다. 필요한 것이 있나요?",
            "options": [
                {"text": "물건을 사고 싶어요.", "nextId": 5},
                {"text": "다음에요.", "nextId": 6}
            ]
        }
    ]
}

2) JSON 파일 불러오기

Unity에서 JSON 파일을 읽어와 대화 데이터를 파싱하는 스크립트를 작성합니다.

using System.Collections.Generic;
using UnityEngine;
using TMPro;

[System.Serializable]
public class DialogueOption
{
    public string text;      // 선택지 텍스트
    public int nextId;       // 다음 대화 ID
}

[System.Serializable]
public class DialogueNode
{
    public int id;           // 대화 ID
    public string speaker;   // 대화자 이름
    public string text;      // 대화 내용
    public List<DialogueOption> options;  // 선택지
}

[System.Serializable]
public class DialogueList
{
    public List<DialogueNode> conversation;
}

public class DialogueManager : MonoBehaviour
{
    public TextMeshProUGUI chatLog;       // 채팅 로그 UI
    public TextMeshProUGUI optionsText;   // 선택지 UI
    private int currentId = 1;            // 현재 대화 ID
    private Dictionary<int, DialogueNode> dialogue;

    void Start()
    {
        // JSON 파일 로드 및 대화 데이터 초기화
        LoadDialogue();
        DisplayDialogue(currentId);
    }

    void LoadDialogue()
    {
        // Resources 폴더에서 JSON 파일을 읽어옴
        TextAsset file = Resources.Load<TextAsset>("dialogue");
        DialogueList dialogueList = JsonUtility.FromJson<DialogueList>(file.text);

        // 대화 데이터를 Dictionary로 변환
        dialogue = new Dictionary<int, DialogueNode>();
        foreach (DialogueNode node in dialogueList.conversation)
        {
            dialogue.Add(node.id, node);
        }
    }

    void DisplayDialogue(int id)
    {
        // 현재 대화 노드를 불러옴
        var node = dialogue[id];
        chatLog.text = node.speaker + ": " + node.text + "\n";

        // 선택지를 UI에 표시
        optionsText.text = "";
        foreach (var option in node.options)
        {
            optionsText.text += option.text + "\n";
        }
    }

    public void OnOptionSelected(int nextId)
    {
        // 선택한 옵션에 따라 다음 대화로 이동
        currentId = nextId;
        DisplayDialogue(currentId);
    }
}

3) 선택지 클릭 처리

플레이어가 선택지를 클릭하면, 해당 선택지에 따라 다음 대화로 넘어가도록 처리합니다. UI 버튼을 사용하여 각 선택지를 표시하고, 선택한 옵션에 맞춰 OnOptionSelected 메서드를 호출하면 됩니다.

2. ScriptableObject를 사용한 대사 관리

ScriptableObject는 Unity에서 간편하게 데이터를 저장하고 관리할 수 있는 구조입니다. ScriptableObject로 대사 데이터를 저장하는 방법도 있습니다.

1) ScriptableObject 클래스 정의

먼저, 대화 데이터를 저장할 ScriptableObject 클래스를 정의합니다.

using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "NewDialogue", menuName = "Dialogue System/Dialogue")]
public class Dialogue : ScriptableObject
{
    public int id;                   // 대화 ID
    public string speaker;           // 대화자 이름
    public string text;              // 대화 내용
    public List<DialogueOption> options;  // 선택지
}

2) ScriptableObject 데이터 생성

프로젝트 창에서 우클릭 → Create → Dialogue System → Dialogue를 선택하여 새로운 대화 데이터를 생성합니다. 생성된 ScriptableObject에서 대사와 선택지를 직접 입력할 수 있습니다.

3) ScriptableObject 데이터 불러오기

DialogueManager에서 ScriptableObject 데이터를 불러와 대사를 표시하도록 합니다.

using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class DialogueManager : MonoBehaviour
{
    public TextMeshProUGUI chatLog;
    public TextMeshProUGUI optionsText;
    public List<Dialogue> dialogues;  // ScriptableObject로 생성된 대사 데이터 리스트
    private int currentId = 1;

    void Start()
    {
        DisplayDialogue(currentId);
    }

    void DisplayDialogue(int id)
    {
        // 현재 ID에 해당하는 대화 데이터를 불러옴
        Dialogue currentDialogue = dialogues.Find(d => d.id == id);
        if (currentDialogue != null)
        {
            chatLog.text = currentDialogue.speaker + ": " + currentDialogue.text + "\n";
            optionsText.text = "";

            // 선택지 표시
            foreach (var option in currentDialogue.options)
            {
                optionsText.text += option.text + "\n";
            }
        }
    }

    public void OnOptionSelected(int nextId)
    {
        // 선택한 옵션에 맞춰 대화 이동
        currentId = nextId;
        DisplayDialogue(currentId);
    }
}

3. 대사 추가 요약

  1. JSON: JSON 파일로 대사 구조를 정의하고, Unity에서 불러와 대사 데이터를 관리할 수 있습니다. 대규모 스토리나 분기 구조가 필요할 때 유용합니다.
  2. ScriptableObject: Unity 내에서 데이터 관리를 쉽게 하고 싶을 때는 ScriptableObject를 사용하여 대사를 입력하고 관리할 수 있습니다.

'개인 프로젝트' 카테고리의 다른 글

ui구현  (0) 2024.09.14
채팅내에 이미지 삽입  (0) 2024.09.14
세이브 시스템  (0) 2024.09.14
채팅형 스토리 게임- 유니티 기반 단계 설명  (1) 2024.09.14
기획서작성  (0) 2024.08.28