工作項目中我們經常會使用到將錯誤的提示,成功的提示顯示到屏幕上更加有利於玩家的觀看和了解,這時候我們需要的操作就是將我們需要顯示的內容發送到顯示屏幕上,然后實現文本內容的顯示,如下圖所示:

實現這個功能我們所需要的兩個腳本內容和一個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();
}
}
}
上面兩端代碼就能夠較為輕松的實現 文本提示等內容的顯示,這個東西我們可以設置我們的一個小工具類,當我們需要進行一些內容的顯示的時候就可以用到上面這個方法了!!!!!!!!!!!!!!!!!!!!!!!!!!
