Unity용 대화 시스템

games의 대화 시스템은 게임 세계 내 플레이어와 캐릭터 간의 대화형 몰입형 대화를 가능하게 하는 메커니즘입니다. 이는 플레이어가 비플레이어 캐릭터(NPC) 또는 기타 개체와 소통할 수 있는 통신 채널 역할을 하며 스토리텔링, 퀘스트 진행, 캐릭터 개발 및 세계 구축을 위한 수단을 제공합니다.

대화 시스템의 주요 목표는 플레이어가 선택을 하고, 게임 내러티브에 영향을 미치고, 게임 내 캐릭터와의 관계를 형성할 수 있도록 하여 플레이어에게 역동적이고 매력적인 경험을 제공하는 것입니다. 잘 설계된 대화 시스템은 플레이어의 몰입도, 감정적 투자 및 재생성을 향상시킬 수 있습니다.

Unity의 게임 개발에 있어서 완전한 대화 시스템을 처음부터 만드는 것은 상당히 광범위할 수 있지만 시작하려면 간단한 예제부터 시작하는 것이 가능합니다. 아래 예에서는 C#Unity UI 시스템을 사용하는 기본 텍스트 기반 대화 시스템을 다룹니다. 이는 단지 시작점일 뿐이며 특정 요구 사항에 따라 확장하고 사용자 정의할 수 있다는 점을 기억하세요.

대화 관리자 만들기

  • 새 스크립트를 만들고 이름을 "DialogueManager"로 지정한 다음 그 안에 아래 코드를 붙여넣습니다.
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class DialogueManager : MonoBehaviour
{
    public Text dialogueText;
    public Button choice1Button;
    public Button choice2Button;
    public Button nextButton;

    private Dialogue currentDialogue;
    private int currentLineIndex = 0;

    void Start()
    {
        // You can load your dialogue data from an external source (e.g., JSON, XML) or create it programmatically.
        // For simplicity, we'll create a sample dialogue here.
        currentDialogue = CreateSampleDialogue();

        // Set up event listeners for buttons
        choice1Button.onClick.AddListener(OnChoice1Selected);
        choice2Button.onClick.AddListener(OnChoice2Selected);
        nextButton.onClick.AddListener(OnNextButtonClicked);

        // Start the dialogue
        StartDialogue();
    }

    private void StartDialogue()
    {
        currentLineIndex = 0;
        DisplayLine(currentDialogue.lines[currentLineIndex]);
    }

    private void DisplayLine(DialogueLine line)
    {
        dialogueText.text = line.text;
        choice1Button.gameObject.SetActive(line.hasChoice);
        choice2Button.gameObject.SetActive(line.hasChoice);
        nextButton.gameObject.SetActive(!line.hasChoice);
    }

    private void OnNextButtonClicked()
    {
        currentLineIndex++;
        if (currentLineIndex < currentDialogue.lines.Length)
        {
            DisplayLine(currentDialogue.lines[currentLineIndex]);
        }
        else
        {
            // Dialogue is over
            EndDialogue();
        }
    }

    private void OnChoice1Selected()
    {
        HandleChoice(currentDialogue.lines[currentLineIndex].choice1);
    }

    private void OnChoice2Selected()
    {
        HandleChoice(currentDialogue.lines[currentLineIndex].choice2);
    }

    private void HandleChoice(Choice choice)
    {
        // Handle the chosen choice (e.g., change variables, trigger events)
        Debug.Log("Selected Choice: " + choice.text);

        // Advance to the next line
        currentLineIndex++;
        DisplayLine(currentDialogue.lines[currentLineIndex]);
    }

    private void EndDialogue()
    {
        // Reset the dialogue UI or close the dialogue box
        Debug.Log("End of Dialogue");
    }

    // Sample dialogue data (you can replace this with loading from an external source)
    private Dialogue CreateSampleDialogue()
    {
        Dialogue dialogue = new Dialogue();

        dialogue.lines = new DialogueLine[]
        {
            new DialogueLine("Hello there! Welcome to the Unity dialogue system example.", false),
            new DialogueLine("What would you like to do?", true, new Choice("Go on an adventure"), new Choice("Stay here")),
            new DialogueLine("Great choice! Have a fantastic adventure!", false),
            new DialogueLine("That's okay. Sometimes staying in one place can be just as exciting!", false),
            new DialogueLine("Thanks for trying out the Unity dialogue system example!", false)
        };

        return dialogue;
    }
}

[System.Serializable]
public class Dialogue
{
    public DialogueLine[] lines;
}

[System.Serializable]
public class DialogueLine
{
    public string text;
    public bool hasChoice;
    public Choice choice1;
    public Choice choice2;

    public DialogueLine(string text, bool hasChoice, Choice choice1 = null, Choice choice2 = null)
    {
        this.text = text;
        this.hasChoice = hasChoice;
        this.choice1 = choice1;
        this.choice2 = choice2;
    }
}

[System.Serializable]
public class Choice
{
    public string text;

    public Choice(string text)
    {
        this.text = text;
    }
}

DialogueManager 스크립트에 대해 Unity에서 UI 텍스트 및 버튼 개체를 설정하려면 아래 단계를 따르세요.

  • Unity 편집기에서 Hierarchy 창을 마우스 오른쪽 버튼으로 클릭하고 "UI -> Text"을 선택하여 새 UI 텍스트 개체를 만듭니다.
  • UI 텍스트 개체의 이름을 다음으로 바꿉니다. "DialogueText."
  • 마찬가지로 세 개의 UI 버튼 개체를 만듭니다. 하나는 선택 1, 하나는 선택 2, 다른 하나는 "Next" 버튼(대화 진행용)입니다.
  • 버튼 이름을 각각 "Choice1Button," "Choice2Button," 및 "NextButton"로 지정합니다.
  • 원하는 레이아웃에 따라 UI 텍스트와 버튼을 캔버스에 배치합니다. UI 텍스트를 화면 중앙에 배치하고 버튼을 텍스트 상자 아래에 배치할 수 있습니다.
  • 게임의 시각적 스타일에 맞게 UI 텍스트의 텍스트 글꼴, 크기, 색상 및 기타 속성을 조정합니다.
  • 색상 및 텍스트 레이블 변경 등 UI 버튼의 모양을 사용자 정의합니다.
  • Unity 편집기에서 "DialogueManager" GameObject(스크립트를 attach하기 위해 만든 것)를 선택합니다.
  • Inspector 창에 "Dialogue Manager" 스크립트 구성요소가 표시됩니다. 계층 구조 창의 UI 텍스트 및 버튼 개체를 스크립트 구성 요소의 해당 공개 필드로 끌어서 놓습니다.
  • 이러한 참조를 할당함으로써 DialogueManager 스크립트는 장면의 UI 텍스트 및 버튼에 액세스할 수 있으므로 대화 중에 필요에 따라 텍스트 콘텐츠를 업데이트하고 가시성을 제어할 수 있습니다.
  • 변수 변경 사항을 저장하려면 장면을 저장하세요.

게임을 실행하거나 대화 트리거와 상호 작용할 때 DialogueManager는 캔버스에서 참조된 UI 요소를 사용하여 대화 텍스트와 선택 사항을 표시할 수 있어야 합니다.

결론

게임의 효과적인 대화 시스템은 플레이어에게 가상 세계에 대한 선택 의지, 영향력 및 참여감을 제공하여 게임 경험을 더욱 풍부하고 매력적으로 만듭니다. 게임 내러티브와 대화형 스토리텔링이 더욱 정교해짐에 따라 대화 시스템은 플레이어의 여정을 형성하고 기억에 남는 게임 경험을 만드는 데 점점 더 중요한 역할을 합니다.

추천 기사
Unity에서 파쿠르 시스템 구현
Unity용 헬리콥터 컨트롤러
Unity의 2D 플랫폼 게임 캐릭터 컨트롤러에 이중 점프 지원 추가
Unity에서 크레인 제어를 만드는 방법
Unity용 자동차 컨트롤러
캐릭터 컨트롤러 Unity에서 강체를 푸시하는 기능을 추가하는 방법
Unity용 비행기 컨트롤러