新建Panel
canvas----屏幕空间对话框不会充满屏幕world space reset canvas重新新设置位置 ----event camera拖拽main camera----渲染顺序order in layer 10
Panel—锚点居中–调解大小(14,4)—调解透明度—source image背景图片—取消显示,添加文本框用于显示对话。
TEXT—调解大小,非字体大小,文本框的scale(“R”键–“T”键)
显示说话人的头像—panel下添加image—调大小位置–添加图片
老人下挂载的图片用于提示按键R,默认不显示,显示时按下R键可以弹出对话框。
Panel拖拽到Talk UI上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TalkButton : MonoBehaviour
{
public GameObject Button;
public GameObject talkUI;
private void OnTriggerEnter2D(Collider2D other)
{
Button.SetActive(true);
}
private void OnTriggerExit2D(Collider2D other)
{
Button.SetActive(false);
}
private void Update()//总是检测是否处于启动的状态和是否按下R键
{
if (Button.activeSelf && Input.GetKeyDown(KeyCode.R))
{
talkUI.SetActive(true);//如果处于启动状态并按下R,状态变为true,对话框显示
}
}
}
读取对话文档text asset
新建脚本编写对话系统–DialogSystem挂载到空对象或panel上,panel下的text、image和对话文本分别拖拽到代码相应位置,Start coroutine实现逐个显示文字。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogSystem : MonoBehaviour
{
[Header("UI组件")]
public Text textLable;//文本框
public Image faceImage;//头像
[Header("文本文件")]
public TextAsset textfile;
public int index;//序号
public float textSpeed;
bool textFished;//判断是否输入完
List<string> textList = new List<string>();//列表
[Header("头像")]
public Sprite face01, face02;//出现A01,出现B02
void Awake()
{
GetTextFromFile(textfile);
}
private void OnEnable()//开始就是文本中的第一句话
{
textFished = true;
StartCoroutine(SetTextUI());
}
void Update()
{
if (Input.GetKeyDown(KeyCode.R) && index == textList.Count)//对话结束
{
gameObject.SetActive(false);//关闭对话框
index = 0;
return;
}
if (Input.GetKeyDown(KeyCode.R) && textFished)
{
StartCoroutine(SetTextUI());
}
}
void GetTextFromFile(TextAsset file)//从文件中获得文本
{
textList.Clear();//清空列表
index = 0;//序号清零
var linedata = file.text.Split('\n');//文本按行分割,数组
foreach (var line in linedata)
{
textList.Add(line);
}
}
IEnumerator SetTextUI()
{
textFished = false;
textLable.text = "";//清空文本框
switch (textList[index])//换头像
{
case "A":
faceImage.sprite = face01;
index++;
break;
case "B":
faceImage.sprite = face02;
index++;
break;
}
for (int i = 0; i < textList[index].Length; i++)
{
textLable.text += textList[index][i];
yield return new WaitForSeconds(textSpeed);//文字输出速度
}
textFished = true;
index++;
}
}
根据B站麦扣教学完成,文章仅用于记录。