如何在Unity中显示类似于Android中的Toast消息?

Unity中有类似Toast消息的东西,除了GUI之外,类似于android。在android中,使用一行代码很容易。

public void buttonclick() { // Message to show } 

您可以使用Text组件和Mathf.Lerp函数执行此操作,方法是将Text淡入Color.clear颜色,等待一段时间然后淡出和淡出。 这篇文章描述了如何使用简单的fadeInAndOut函数来做到这fadeInAndOut 。 在淡化文本之前,获取原始文本颜色,然后启用文本组件。 淡出后,恢复颜色,然后禁用文本组件。

这是一个带有Text组件的简化吐司:

 void Start() { showToast("Hello", 2); } public Text txt; void showToast(string text, int duration) { StartCoroutine(showToastCOR(text, duration)); } private IEnumerator showToastCOR(string text, int duration) { Color orginalColor = txt.color; txt.text = text; txt.enabled = true; //Fade in yield return fadeInAndOut(txt, true, 0.5f); //Wait for the duration float counter = 0; while (counter < duration) { counter += Time.deltaTime; yield return null; } //Fade out yield return fadeInAndOut(txt, false, 0.5f); txt.enabled = false; txt.color = orginalColor; } IEnumerator fadeInAndOut(Text targetText, bool fadeIn, float duration) { //Set Values depending on if fadeIn or fadeOut float a, b; if (fadeIn) { a = 0f; b = 1f; } else { a = 1f; b = 0f; } Color currentColor = Color.clear; float counter = 0f; while (counter < duration) { counter += Time.deltaTime; float alpha = Mathf.Lerp(a, b, counter / duration); targetText.color = new Color(currentColor.r, currentColor.g, currentColor.b, alpha); yield return null; } } 

您可以使用:SSTools.Message()。

我在youtube上找到了速度指南

在看到@Programmer的答案后,我对如何显示文本有一个简单的想法。我使用相同的按钮来显示和隐藏文本。

 public class Toast : MonoBehaviour { public Button btn; public Text txt; // Use this for initialization void Start() { txt.enabled = false; } // Update is called once per frame void Update () { } //Button click function public void Show() { if (txt.isActiveAndEnabled) { txt.enabled = false; btn.GetComponentInChildren().text = "Show"; } else { txt.enabled = true; btn.GetComponentInChildren().text = "Hide"; } } }