Certainly! Here's an example of how you can implement the NPC dialogue system in Unity using C#:
DialogueManager.cs:
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour
{
public Text dialogueText;
private Dialogue currentDialogue;
public void StartDialogue(Dialogue dialogue)
{
currentDialogue = dialogue;
// Do any other setup here (e.g., display NPC portrait, play voice acting, etc.)
// Display the first dialogue message
DisplayNextMessage();
}
public void DisplayNextMessage()
{
if (currentDialogue == null)
return;
if (currentDialogue.IsDialogueFinished())
{
EndDialogue();
return;
}
DialogueMessage message = currentDialogue.GetNextMessage();
dialogueText.text = message.text;
// Do any other visual updates here (e.g., animate text, display character portrait, etc.)
}
public void EndDialogue()
{
currentDialogue = null;
// Do any necessary cleanup here (e.g., hide text box, reset variables, etc.)
}
}
DialogueTrigger.cs (attached to NPCs):
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
public Dialogue dialogue;
public DialogueManager dialogueManager;
private bool canInteract = false;
private void Update()
{
if (canInteract && Input.GetKeyDown(KeyCode.E))
{
StartDialogue();
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
canInteract = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
canInteract = false;
}
}
private void StartDialogue()
{
dialogueManager.StartDialogue(dialogue);
}
}
Dialogue.cs:
[System.Serializable]
public class Dialogue
{
public DialogueMessage[] messages;
private int currentIndex = 0;
public DialogueMessage GetNextMessage()
{
if (currentIndex >= messages.Length)
{
return null;
}
DialogueMessage message = messages[currentIndex];
currentIndex++;
return message;
}
public bool IsDialogueFinished()
{
return currentIndex >= messages.Length;
}
}
[System.Serializable]
public class DialogueMessage
{
public string text;
// Add any other necessary properties here (e.g., speaker, voice clip, etc.)
}
Make sure to assign the dialogue field in the DialogueTrigger script with the appropriate dialogue you want each NPC to have. Also, make sure to attach the DialogueManager script to your UI canvas and set up the appropriate UI elements (e.g., text box) and references to those elements in the DialogueManager script.
This is just a basic implementation to get you started. Feel free to modify and expand the scripts based on your specific game requirements and design choices.