C# Unity NPC 대화 만들기

삐얅·2024년 8월 6일

유니티

목록 보기
19/20

1. 개요

플레이어에게 재화가 있었으나 사용처가 마땅하지 않아 팀 회의를 거친 끝에 플레이어 캐릭터의 스탯을 강화해주는 아이템을 파는 NPC를 만들어주기로 결정해 해당 기능을 구현하게 되었다.

2. 코드

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

public class NPCInteraction : MonoBehaviour
{
    public GameObject dialogueUI;
    public TextMeshProUGUI speakerText;
    public TextMeshProUGUI dialogueText;
    public Button upgrade;
    public Button exit;
    public DialogueData dialogueData;
    public LayerMask playerLayer;

    public bool isPlayerRange = false;
    public bool isDialogue = false;

    private int currentLineIndex = 0;

    private void Start()
    {
        dialogueUI.SetActive(false);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(((1 << collision.gameObject.layer) & playerLayer) != 0)
        {
            isPlayerRange = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (((1 << collision.gameObject.layer) & playerLayer) != 0)
        {
            isPlayerRange = false;
        }
    }

    public void StartDialogue(DialogueData dialogue)
    {
        isDialogue = true;
        UIManager.Instance.OpenUI(dialogueUI);
        dialogueData = dialogue;
        currentLineIndex = 0;
        CurrnetLine();
    }

    public void NextDialogue()
    {
        if(currentLineIndex < dialogueData.dialogueLines.Count - 1)
        {
            currentLineIndex++;
            CurrnetLine();
        }
        
        else
        {
            EndDialogue();
        }
    }

    private void CurrnetLine()
    {
        DialogueData.DialogueLine line = dialogueData.dialogueLines[currentLineIndex];
        speakerText.text = line.name;
        dialogueText.text = line.dialogueText;
    }

    private void EndDialogue()
    {
        UIManager.Instance.CloseCurrentUI();
    }
}

버튼 부분은 아직 미구현상태지만 Scriptable Object에서 리스트를 이용해 대화문들을 만들어주고 이를 리스트의 인덱스를 변경해 주는 것으로 대화문이 진행 되게끔하고 크기를 벗어나면 대화문을 닫는 구조로 만들었다.

0개의 댓글