The Beauty of unity Dialogue System

Links to the original text: https://github.com/ChinarG/TUTORIAL--Dialog-System

 

Game effects:

 

1

Create XML Document -- Create the required XML document

 

Note the path:

My XML document "Dialog.xml" is in a Data directory created under the Assets directory

If the name is different, it needs to be renamed.

Or directly modify the read path in the parsing XML code for your own path

Document. Load (Application. dataPath +"/ Data / Dialog. xml); // Load XML content

<?xml version="1.0" encoding="utf-8"?>
<!-- Dialog System ; Background ; Image ; Music -->
<root>
  <bg>Background 1</bg>
  <bgm>Sound of rain</bgm>
  <say>
    <name>captain</name>
    <image>Captain Qujing1</image>
    <sound>1 poems on flowers</sound>
    <content>My little fish, you wake up,Do you remember knowing the morning?</content>
  </say>
  <say>
    <name>Xiu Xiu</name>
    <image>Xiu Xiu 1</image>
    <sound>2 poems on flowers</sound>
    <content>Last night you said, may the night never open.</content>
  </say>
  <say>
    <name>captain</name>
    <image>Captain Qujing1 2</image>
    <sound>3 poems on flowers</sound>
    <content>Your fragrant cheek slips gently</content>
  </say>
  <say>
    <name>Xiu Xiu</name>
    <image>Xiu Xiu 2</image>
    <sound>4 poems on flowers</sound>
    <content>Is it your tears or mine?</content>
  </say>
  <bg>Background 2</bg>
  <say>
    <name>Xiu Xiu</name>
    <image>Xiu Xiu 3</image>
    <sound>5 poems on flowers</sound>
    <content>The season of kissing goodbye for the first time</content>
  </say>
  <say>
    <name>captain</name>
    <image>Captain Qujing1 3</image>
    <sound>6 poems on flowers</sound>
    <content>Haven't you already cried?</content>
  </say>
  <bg>Background 3</bg>
  <say>
    <name>captain</name>
    <image>Captain Qujing1 4</image>
    <sound>7 poems on flowers</sound>
    <content>My fingertips still remember</content>
  </say>
  <say>
    <name>Xiu Xiu</name>
    <image>Xiu Xiu 4</image>
    <sound>8 poems on flowers</sound>
    <content>Your flurried heartbeat</content>
  </say>
  <say>
    <name>captain</name>
    <image>Captain Qujing1</image>
    <sound>9 poems on flowers</sound>
    <content>In the warm body fragrance</content>
  </say>
  <bg>Background 4</bg>
  <say>
    <name>Xiu Xiu</name>
    <image>Xiu Xiu 1</image>
    <sound>10 poems on flowers</sound>
    <content>That long hair is floating.</content>
  </say>
</root>

2

Audio Manager - Audio Manager script

 

Hang this script on GameObject that guarantees activation and add two AudioSource components

By dragging

Drag 2 AudioSource components to_in the Inspecter panel

Background sound: BgmAudioSource and sound effects: in the SeAudioSource box

using UnityEngine;


/// <summary>
/// Sound Management Class
/// </summary>
public class AudioManager : MonoBehaviour
{
    public static AudioManager Instance;       //Single case
    public        AudioSource  BgmAudioSource; //Background sound
    public        AudioSource  SeAudioSource;  //Sound effects
    private       AudioClip    _clip;          //Music document


    /// <summary>
    /// Initialization function
    /// </summary>
    void Start()
    {
        Instance = this;
    }


    /// <summary>
    /// Play Background Sound
    /// </summary>
    public void PlayBgm(string inName)
    {
        _clip               = Resources.Load<AudioClip>(inName); //Loading music files
        BgmAudioSource.clip = _clip;                             //Change Music File to Clip Default File
        BgmAudioSource.Play();                                   //Play music
    }


    /// <summary>
    /// Playing sound effects
    /// </summary>
    public void PlaySe(string inName)
    {
        _clip = Resources.Load<AudioClip>(inName); //Loading music files
        SeAudioSource.PlayOneShot(_clip);          //Play the sound and it's over.
    }


    /// <summary>
    /// Stop background sound
    /// </summary>
    public void StopBgm()
    {
        BgmAudioSource.Stop(); //Stop Player
    }
}

3

UI Manager-Interface Interactive Control

 

Hang this script on GameObject that guarantees activation

By dragging

Inspecter - Panel: Add 6 declared objects separately

using UnityEngine;
using System.Xml;                  //Quote XML
using UnityEngine.UI;              //Quote UI
using System.Collections.Generic;  //Reference set
using UnityEngine.SceneManagement; //Reference namespaces



/// <summary>
/// Enumeration instruction type
/// </summary>
public enum CommandType
{
    Say, //speak
    Bgm, //Background sound
    Bg   //background
}



/// <summary>
/// Base Class: Instruction Class
/// </summary>
public class Command
{
    public CommandType AllType; //Define member variable type objects
}



/// <summary>
/// Speech Instruction Class: Inheritance Instruction Base Class
/// </summary>
public class Say : Command
{
    public string Name;    //Name
    public string Image;   //picture
    public string Sound;   //Music
    public string Content; //content
}



/// <summary>
/// Background Voice Instruction Class: Inheritance Instruction Base Class
/// </summary>
public class Bgm : Command
{
    public string Name; //Name
}



/// <summary>
/// Background Instruction Class: Inheritance Instruction Base Class
/// </summary>
public class Bg : Command
{
    public string Name; //Name
}



/// <summary>
/// Dialogue system
/// </summary>
public class DialogUI : MonoBehaviour
{
    public  List<Command> Commands = new List<Command>(); //Declare a List array type as: Command
    private int           _index   = 0;                   //The default index is 0
    public  GameObject    GameImage;                      //Game interface
    public  GameObject    ReloadBut;                      //Reopen button
    public  Image         BgImage;                        //Background map
    public  Image         HeadPortrait;                   //Head portrait
    public  Text          NameText;                       //Name text
    public  Text          ConttentText;                   //Content text
    private bool          _isExecute = false;             //Whether to Execute Commands: Default Not to Execute


    /// <summary>
    /// Initialization method
    /// </summary>
    void Start()
    {
        AnalysisXml();                                                                            //Call parsing XML methods
        GameObject.Find("StartGameButton").GetComponent<Button>().onClick.AddListener(StartGame); //Add listening events to the Start Game button
    }


    /// <summary>
    /// Update function
    /// </summary>
    void Update()
    {
        if (Input.GetMouseButtonDown(0)           && _isExecute == true ||
            Input.GetKeyDown(KeyCode.KeypadEnter) && _isExecute == true) //If you press the left mouse button or Enter
        {
            OneByOneExecuteCommand(); //Execute dialog command functions
        }
    }


    /// <summary>
    /// Start the game
    /// </summary>
    public void StartGame()
    {
        GameImage.SetActive(true); //Activate the Game Interface
        _isExecute = true;         //Game Start: You can start executing code
        OneByOneExecuteCommand();  //When the game page is activated, it is executed once.
    }


    /// <summary>
    /// Execute dialog command functions
    /// </summary>
    public void OneByOneExecuteCommand()
    {
        if (_index >= Commands.Count) //Subscript crossing: Read through
        {
            ReloadBut.SetActive(true);                                         //Activate overload button
            ReloadBut.GetComponent<Button>().onClick.AddListener(ReloadScene); //Add overload scenario listening events to buttons
            _isExecute = false;                                                //Close Execution Command
            return;
        }

        Command command = Commands[_index++]; //Self-Increasing: Take out a command

        switch (command.AllType)
        {
            //If the type is: Say speaks
            case CommandType.Say:
                Say say             = (Say) command;                     //Instantiate Say object say
                HeadPortrait.sprite = Resources.Load<Sprite>(say.Image); //Change the Avatar
                NameText.text       = say.Name;                          //character
                ConttentText.text   = say.Content;                       //Speech content
                if (!string.IsNullOrEmpty(say.Sound))                    //If the sound effect name is not empty
                {
                    AudioManager.Instance.PlaySe(say.Sound); //Play sound effects
                }
                break;

            //If the type is: Bgm background music
            case CommandType.Bgm:
                Bgm bgm = (Bgm) command;                 //Instantiate bgm object bgm
                AudioManager.Instance.PlayBgm(bgm.Name); //Play background music
                OneByOneExecuteCommand();                //Direct implementation of the next article
                break;

            //If the type is: Bg background
            case CommandType.Bg:
                Bg bg          = (Bg) command;                    //Instantiate bg object bg
                BgImage.sprite = Resources.Load<Sprite>(bg.Name); //Change Background Pictures
                OneByOneExecuteCommand();                         //Direct implementation of the next article
                break;
        }
    }


    /// <summary>
    /// overload scenario
    /// </summary>
    public void ReloadScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //Overload the current scenario
    }


    /// <summary>
    /// resolution XML
    /// </summary>
    private void AnalysisXml()
    {
        XmlDocument document = new XmlDocument();                 //Instantiate an xml document
        document.Load(Application.dataPath + "/Data/Dialog.xml"); //Loading XML content
        XmlElement rootEle = document.LastChild as XmlElement;    //Root node
        foreach (XmlElement ele in rootEle.ChildNodes)            //Traversing all the child nodes of the root node
        {
            if (ele.Name == "bgm") //If the name of the element is the node "bgm" in the XML document
            {
                Bgm bgm     = new Bgm();
                bgm.AllType = CommandType.Bgm;
                bgm.Name    = ele.InnerText;
                Commands.Add(bgm); //Add to Commands
            }
            else if (ele.Name == "bg")
            {
                Bg bg      = new Bg();
                bg.AllType = CommandType.Bg;
                bg.Name    = ele.InnerText;
                Commands.Add(bg);
            }
            else if (ele.Name == "say")
            {
                Say say     = new Say();
                say.AllType = CommandType.Say;
                say.Name    = ele.ChildNodes[0].InnerText;
                say.Image   = ele.ChildNodes[1].InnerText;
                say.Sound   = ele.ChildNodes[2].InnerText;
                say.Content = ele.ChildNodes[3].InnerText;
                Commands.Add(say);
            }
        }
    }
}

Finish - Test Running


Direct Click to run Or Alt+P

Attachment: GitHub Project Case of Chinar

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Keywords: xml github encoding

Added by networkguy on Fri, 04 Oct 2019 02:42:52 +0300