您的位置:首页 > 产品设计 > UI/UE

UGUI 实现文本打字效果

2015-06-19 08:53 651 查看
孙广东 2015.6.17
熟悉NGUI的人可定知道了。
但是NGUI弄的有些繁琐, 感兴趣的人可以将NGUI的TypewriterEffect类转成 UGUI特定的,因为有些以来的其他脚本,不爱弄。

我这个只是简化的内容。够用了



using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

/// <summary>
/// 此脚本是能够将文本字符串随着时间打字或褪色显示。
/// </summary>

[RequireComponent(typeof(Text))]
[AddComponentMenu("Typewriter Effect")]
public class TypewriterEffect : MonoBehaviour
{
    public UnityEvent myEvent;
    public int charsPerSecond = 0;
    // public AudioClip mAudioClip;             // 打字的声音,不是没打一个字播放一下,开始的时候播放结束就停止播放
    private bool isActive = false;

    private float timer;
    private string words;
    private Text mText;

    void Start()
    {
        if (myEvent == null)
            myEvent = new UnityEvent();

        words = GetComponent<Text>().text;
        GetComponent<Text>().text = string.Empty;
        timer = 0;
        isActive = true;
        charsPerSecond = Mathf.Max(1, charsPerSecond);
        mText = GetComponent<Text>();
    }

    void ReloadText()
    {
        words = GetComponent<Text>().text;
        mText = GetComponent<Text>();
    }

    public void OnStart()
    {
        ReloadText();
        isActive = true;
    }

    void OnStartWriter()
    {
        if (isActive)
        {
            try
            {
                mText.text = words.Substring(0, (int) (charsPerSecond * timer));
                timer += Time.deltaTime;
            }
            catch (Exception)
            {
                OnFinish();
            }
        }
    }

    void OnFinish()
    {
        isActive = false;
        timer = 0;
        GetComponent<Text>().text = words;
        try
        {
             myEvent.Invoke();
        }
        catch (Exception)
        {
            Debug.Log("问题");
        }
    }

    void Update()
    {
        OnStartWriter();
    }
}


还没有完

想使用前几天 介绍的插件 TextFX 实现这个功能:

还有就是使用 插件 DoTween 实现这个动能:

Text (Unity UI 4.6)

DOText(string to, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null)Tweens the target's text to the given value.
richTextEnabled If TRUE (default), rich text will be interpreted correctly while animated, otherwise all tags will be considered as normal text.
scramble The type of scramble mode to use, if any.
If different than
ScrambleMode.None
the string will appear from a random animation of characters, otherwise it will compose itself regularly.
None
(default): no scrambling will be applied.
All/Uppercase/Lowercase/Numerals
: type of characters to be used while scrambling.
Custom
: will use the custom characters in
scrambleChars
.
scrambleChars A string containing the characters to use for custom scrambling. Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: