Hệ thống Dialogue (Hội thoại) cơ bản
C# Code
// 1. ScriptableObject để chứa dữ liệu hội thoại
using UnityEngine;
[CreateAssetMenu(fileName = "New Dialogue", menuName = "Dialogue/Dialogue")]
public class DialogueData : ScriptableObject
{
public string speakerName;
[TextArea(3, 10)]
public string[] sentences;
}
// 2. Script quản lý UI hội thoại
using UnityEngine;
using TMPro;
using System.Collections.Generic;
using System.Collections;
public class DialogueManager : MonoBehaviour
{
public static DialogueManager Instance;
public TextMeshProUGUI nameText;
public TextMeshProUGUI dialogueText;
public GameObject dialogueBox;
private Queue<string> sentences;
void Awake() { Instance = this; }
void Start()
{
sentences = new Queue<string>();
dialogueBox.SetActive(false);
}
public void StartDialogue(DialogueData dialogue)
{
dialogueBox.SetActive(true);
nameText.text = dialogue.speakerName;
sentences.Clear();
foreach (string sentence in dialogue.sentences)
{
sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
public void DisplayNextSentence()
{
if (sentences.Count == 0)
{
EndDialogue();
return;
}
string sentence = sentences.Dequeue();
StopAllCoroutines();
StartCoroutine(TypeSentence(sentence));
}
IEnumerator TypeSentence(string sentence)
{
dialogueText.text = "";
foreach (char letter in sentence.ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(0.02f);
}
}
void EndDialogue()
{
dialogueBox.SetActive(false);
Debug.Log("End of conversation.");
}
}
// 3. Script để kích hoạt hội thoại (gắn vào NPC hoặc trigger)
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
public DialogueData dialogue;
public void TriggerDialogue()
{
DialogueManager.Instance.StartDialogue(dialogue);
}
// Ví dụ: Kích hoạt khi va chạm với Player
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player"))
{
TriggerDialogue();
gameObject.SetActive(false); // Chỉ kích hoạt 1 lần
}
}
}Một hệ thống đơn giản để hiển thị các đoạn hội thoại có nhiều câu và lựa chọn cho người chơi, sử dụng ScriptableObject.