工作项目中我们经常会使用到将错误的提示,成功的提示显示到屏幕上更加有利于玩家的观看和了解,这时候我们需要的操作就是将我们需要显示的内容发送到显示屏幕上,然后实现文本内容的显示,如下图所示:
实现这个功能我们所需要的两个脚本内容和一个Text显示文本内容为:
ugui中 Text上面的组件如下:
下面这个脚本主要实现的是点击进行其中文本内容的显示:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShowContentScript : MonoBehaviour { void Update () { if (Input.GetKeyDown(KeyCode.A)) { PrompPanel.isStartShowText = true; PromptMsg.Instance.Change("小松真帅",Color.red); } if (Input.GetKeyDown(KeyCode.B)) { PrompPanel.isStartShowText = true; PromptMsg.Instance.Change("大荣真丑", Color.black); } } }
下面这个脚本主要实现的是文字内容的显示与消失以及颜色的设置:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PrompPanel : MonoBehaviour {
private Text txt;
private CanvasGroup cg;
[SerializeField]
[Range(0, 3)]
private float showTime = 1f;
private float timer = 0f;
public static bool isStartShowText=false;
void Start()
{
txt = transform.Find("Text").GetComponent<Text>();
cg = transform.Find("Text").GetComponent<CanvasGroup>();
cg.alpha = 0;
}
private void Update()
{
if (isStartShowText)
{
promptMessage(PromptMsg.Instance.Text, PromptMsg.Instance.Color);
isStartShowText = false;
}
}
/// <summary>
/// 提示消息
/// </summary>
private void promptMessage(string text, Color color)
{
txt.text = text;
txt.color = color;
cg.alpha = 0;
timer = 0;
//做动画显示
StartCoroutine(promptAnim());
}
/// <summary>
/// 用来显示动画
/// </summary>
/// <returns></returns>
IEnumerator promptAnim()
{
while (cg.alpha < 1f)
{
cg.alpha += Time.deltaTime * 2;
yield return new WaitForEndOfFrame();
}
while (timer < showTime)
{
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
while (cg.alpha > 0)
{
cg.alpha -= Time.deltaTime * 2;
yield return new WaitForEndOfFrame();
}
}
}
上面两端代码就能够较为轻松的实现 文本提示等内容的显示,这个东西我们可以设置我们的一个小工具类,当我们需要进行一些内容的显示的时候就可以用到上面这个方法了!!!!!!!!!!!!!!!!!!!!!!!!!!