撰写了文章 发布于 2020-09-26 10:52:40
《非法进账日志》开发日记4——角色对话系统试做
UI角色设计还未开始,但事先实验一下怎么写一个通过读取外部文件的对话系统。
首先常规的建立panel text等。
然后再panel层级下建立以下脚本:
public class dialogsystem : MonoBehaviour
{
[Header("UI组件")]
public Text textLabel;
public Image faceImage;
[Header("文字文件")]
public TextAsset textFile;
public int index;//编号,(txt中每一行)
List<string> textList = new List<string>();
public float textSpeed;//文字输出速度
bool textFinished;//此处的bool值是为了携程执行文字输出时,快速得按R键会导致
//前一个携程还没执行完毕,后一个携程开始,导致两个携程互相在文本中加字,从而导致断码,因此要加一个判断不允许两个携程的同时运行。
bool cancelTyping;//该布尔变量主要用于在打字过程中再按交互建使得文字能快速显示
[Header("头像")]
public Sprite face01;
public Sprite face02;
// Start is called before the first frame update
void Awake()//awake函数执行在onenable之前
{
GetTextFromFile(textFile);
index = 0;
}
private void OnEnable()//在物体触发的一开始就调用第一句话
{
textFinished = true;
//textLabel.text = textList[index];
//index++;
StartCoroutine(setTextUI());
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R) && index == textList.Count)
{
gameObject.SetActive(false);
index = 0;
return;
}
if (Input.GetKeyDown(KeyCode.R))
{
if (textFinished && !cancelTyping)
{//文字没打完并且没取消
StartCoroutine(setTextUI());
//括号中是方法名(将一个方法创建成一个携程)
//该方法的作用在于在一个携程执行的过程中插入等待时间或者理解为将完整的方法拆分开来顺序执行。
}
else if (!textFinished)
{
cancelTyping = !cancelTyping;//没完成则切换状态
}
}
}
void GetTextFromFile(TextAsset file)//读取文件的方法
{
textList.Clear();//清空列表
index = 0;
var lineDate=file.text.Split('\n');//text会将文件变成字符数组,按回车切割
foreach(var line in lineDate)
{
textList.Add(line);
}
}
//var变量会自动识别变量类型
IEnumerator setTextUI()//ienumerator是一个携程变量
{
textFinished = false;
textLabel.text = "";//清空一开始的文字
switch (textList[index])
{
case"A":
faceImage.sprite = face01;
index++;
break;
case "B":
faceImage.sprite = face02;
index++;
break;
}//这部分内容主要用于遇到人名时切换头像sprite并跳过该行
int letter = 0;
while (!cancelTyping && letter < textList[index].Length - 1)
{
textLabel.text += textList[index][letter];//将字符串中的字符一个一个加入ui
letter++;
yield return new WaitForSeconds(textSpeed);//携程运行后等待的时间(时间结束后才会运行下一个程序)
}//循环会检测是否取消打字,取消了则跳出循环
textLabel.text = textList[index];
textFinished = true;
index++;
}
}
其中,难点主要在于协程的使用,该方法可以使得同一个方法同时被调用(但如果访问同一个资源的话则会有争抢资源的冲突)。
此外的知识点包括直接public spirite用于改变图片文件。
实现功能有:
读取文件来改变对话内容
按键使得某一行文字逐字输出
在输出的过程中再次按交互键会快速输出
结束了UI自动消失
改变人物头像
此外之后可能需要更新的内容:
1、人物名字输出与改变
2、音乐改变
