Unity各种功能实现之一:对话系统

2023-04-07编程技术147215

最近根据网上的教程学习了一下Unity中的对话系统,将其中一些关键点记录下来作为参考,以后可在此基础上添加更多功能。

1.UI部分的设置。

  对话框由一个panel下面的text和image组成。canvas的render mode推荐设置为World Space,因为这样可以方便使对话框随意设定位置

2.TextAsset

  TextAsset是Unity用来导入文本文件的一个格式。当你拖入一个文本文件到你的项目时,他会被转换为文本资源。支持的文本格式有:    

·    .txt、.html、.htm、.xml、.bytes、.json、.csv

  TextAsset中有用的属性是TextAsset.Text。这个属性是string类型,用来访问TextAsset中的全部文本。

3.DialogueSystem脚本构建

    public Text text;
public Image Image;
public TextAsset textAsset; List<string> textList = new List<string>();
int index = 0;
public float time;
bool textFinished;
bool cancelTyping; public Sprite face1, face2;

  简单来说,实现基础对话框需要以上几个要素,即需要显示的完整文本内容textAsset,每一次对话框能显示的内容textList,需要切换的人物头像face1,face2等。

  最基础的对话系统需要实现:

    将textAsset中的内容按人物分段显示,同时根据说话人切换头像
    文字内容快速逐字显现
    玩家可通过按键跳过前面第二条,立刻显示当前人物要说出的完整句子

TextAsset中的内容一般按一下格式来编辑:    

    A
    XXX,XXXXXXXXX
    B
    XXXXXXXXXXXXXXXX!

  故在初始化时用如下方法分割文本内容并保存到textList中:

void GetTextFromFile(TextAsset file)
{
textList.Clear();
index = 0; var linedata = file.text.Split('\n'); for (int i = 0; i < linedata.Length; i++)
{
textList.Add(linedata[i]);
}
}

  上面第二点文字的逐字出现用协程实现,具体代码如下,其中的bool变量textFinished是用来控制同一时间只有一个相关协程在运行,float变量time控制文字显示的快慢:

IEnumerator SetTextUI(float time)
{
textFinished = false;
text.text = ""; switch (textList[index])
{
case "A":
Image.sprite = face1;
index++;
break;
case "B":
Image.sprite = face2;
index++;
break;
} int letter = 0;
while(!cancelTyping && letter <textList[index].Length -1){
text.text += textList[index][letter];
letter++;
yield return new WaitForSeconds(time);
} text.text = textList[index];
cancelTyping = false;
index++;
textFinished = true;
}

    第三点跳过逐字显示直接显示完整内容是通过bool变量cancelTyping来帮助实现

void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && index == textList.Count)
{
index = 0;
gameObject.SetActive(false);
return;
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (textFinished && !cancelTyping)
{
StartCoroutine(SetTextUI(time));
}
else if (!textFinished)
{
cancelTyping = !cancelTyping;
} }
}

  cancelTyping默认为false,当textFinished为false,即协程正在进行时改变cancelTyping为true即可中断协程。

以上只是基础功能,后续还可以根据需要加上比如按键直接退出对话窗口等功能。

    

  

    

Unity各种功能实现之一:对话系统的相关教程结束。

本文地址:https://www.ufcn.cn/tutorials/2423975.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!