前提知识准备
1.ugui
2.textasset:使用它来访问外部的文档
3.startcoroutine:协程,把其他程序暂时挂起,就等你啦!
一、设置对话框
用ugui设置
一个框
一个放文本的位置
一个放人物的image
二、写剧本
在unity创建text文件,格式
A
吃饭了没
B
吃了
A
吃的啥
B
包子
A
怎么吃的包子
B
用嘴巴!
三、读取文件并用协程实现文字一个又一个敲击上去
[header(“ui组件”)]
public text textlabel;//可以getcontorl替换
public image faceimage;//可以用getcontorl替换
[header(“文本文件”)]
public TextAsset textfile;//可以替换
publci int index;//编号
[header("头像")]
public sprite face01,face02;
bool textfinesh;
//让文档变为字符型,让字符型每一行存储在这个列表里
List<string> textlist=new List<string>();
//开始时读取文件
void Awake()
{
GetTextFromFile(textfile);
}
//不算很完美,我们希望开始的时候就输出第一句话,并滚到第二句话
void OnEnable()
{
//存储行 用行输出
//textlabel.text=textlist[index];
//index++;
Startcoroutine(settextui());
textfinesh=true;
}
//尝试输出文件内容
void update()
{
//假如对话完了 关闭
if(input.getkeydown(keycode.r)&&index==textlist.count)
{
gameobject.setactive(false);//可替换
idnex=0;
return;
}
/ /实现按下r 继续对话
if(input.getkeydown(keycode.r)&&textfinesh==true)
{
//存储行 用行输出
//textlabel.text=textlist[index];
//index++;//下一行
Startcoroutine(settextui());
}
//实现读取文件的功能
void GetTextFromFile(TextAsset file)
{
//因为要写好几个剧本 每个人物对应的剧本都不同
textlist.clear();
index=0;
//用回车来分割,并存在名为linedata的string数组中
var linedata=file.text.split('\n');
foreach(var line in linedata)
{
textlist.add(line);
}
}
IEnumerator settextui()
{
textfinesh=false;
textlable.text="";
switch(textlist[index])
{
case:"A"
faceimage.sprite=face01;
index++;//直接将a略过
break;
case:"B"
faceimage.sprite=face02;
index++;//直接将a略过
index++;
}
for(int i =0;i<textlist[index].length.i++)
{
textlabel.text+=textlist[line][i];
yield return new waitforseconds(0.1f);//等0.1秒
}
textfinesh=true;
index++;
}