Unity之文字提示动画

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/shirln/article/details/97624992

推荐阅读:

      在游戏中,玩家进行了某种操作,往往需要给玩家一种提示,以告诉玩家操作结果:成功或失败提示。用于提示的的方式可以是弹框,也可以是文字渐隐。弹框就是显示一些信息,并带有确定/取消按钮等。文字渐隐就是显示文本,上漂并逐渐隐藏,直到消失。此过程往往只需要1秒左右。

今天就来和大家分享一下文字提示的实现。
(1)首先新建一个文本,用于控制文字的动画的实现:
主要思想:
      定义公共变量颜色和文字内容,方便在编辑器中修改;
      声明文本组件,为其指定文本内容,颜色,初始化位置;
      声明一个浮点数变量,用于控制文字动画的时间。
      在Update中对时间–,判断<0? 结束文字动画:减少透明度,向上移动

/**********
*@author:shirln(博客地址:https://blog.csdn.net/shirln)
*@data:2019.7.29
*@fun:文本提示动画
*/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class FlyText : MonoBehaviour
{

    public Color color;//文字的颜色
    public string content;//文本内容
    Text t;//Text组件

    void Start()
    {
        t = transform.GetComponent<Text>();
        t.text = content;//设置组件
        t.color = color;
        t.rectTransform.anchoredPosition = new Vector2(t.rectTransform.anchoredPosition.x, t.rectTransform.anchoredPosition.y + 30);
    }

    float fadeTimer = 1;
    void Update()
    {
        fadeTimer -= Time.deltaTime;
        t.color = new Color(color.r, color.g, color.b, fadeTimer);
        t.rectTransform.anchoredPosition = new Vector2(t.rectTransform.anchoredPosition.x, t.rectTransform.anchoredPosition.y + (1 - fadeTimer));
        if (fadeTimer < 0)
        {
            GameObject.Destroy(this.gameObject);
        }
    }

}

(2)创建一个游戏对象,为其添加Text组件,按需求设置,添加上述FlyText 脚本。保存在Resources文件夹下的Prefabs/Text_FlyText。
(3)该预制的使用方法:
      在需要文字提示的脚本中添加一个flyText方法,用于实例化预制,并转换为GameObject,设置父物体,获取上述FlyText 脚本组件,为其指定颜色和文本内容。

/**********
*@author:shirln(博客地址:https://blog.csdn.net/shirln)
*@data:2019.7.29
*@fun:获取文字动画脚本,为其指定信息
*/
 void flyText(Vector3 pos,Color color,string content)
    {
        GameObject go = Instantiate(Resources.Load<GameObject>("Prefabs/Text_FlyText"), pos, Quaternion.identity) as GameObject;
        go.transform.SetParent(GameObject.Find("Canvas").transform);
        FlyText ft = go.GetComponent<FlyText>();
        ft.color = color;
        ft.content = content;
    }

(4)调用flyText方法:

flyText(new Vector3(0, 0, 0), new Color(1, 0, 0, 1), "文字提示内容");

例如:我需要在游戏开始界面,点击开始按钮时提示文字“进入游戏”

/**********
*@author:shirln(博客地址:https://blog.csdn.net/shirln)
*@data:2019.7.29
*@fun:具体调用方法
*/
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class StartScene : MonoBehaviour {

    public void StartGame()
    {
        flyText(new Vector3(0, 0, 0), new Color(1, 0, 0, 1), "文字提示内容");
    }


     void flyText(Vector3 pos,Color color,string content)
    {
        GameObject go = Instantiate(Resources.Load<GameObject>("Prefabs/Text_FlyText"), pos, Quaternion.identity) as GameObject;
        go.transform.SetParent(GameObject.Find("Canvas").transform);
        FlyText ft = go.GetComponent<FlyText>();
        ft.color = color;
        ft.content = content;
    }

}

猜你喜欢

转载自blog.csdn.net/shirln/article/details/97624992