C# script to make fading in letter by letter text effect with sound effect playing after letters.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class LetterSound : MonoBehaviour {
    [SerializeField] private Text textToUse;
    [SerializeField] private bool useThisText = false;
    [TextAreaAttribute(4, 15)]
    [SerializeField] private string textToShow;
    [SerializeField] private bool useTextText = false;

    [SerializeField] private float fadeSpeedMultiplier = 0.25f;
    [SerializeField] private bool fade = false;

    [SerializeField] private AudioSource audioSource;
    [SerializeField] private bool useThisAudioSource = false;
    [SerializeField] private bool playSound = false;

    private float colorFloat = 0.1f;
    private int colorInt;
    private int letterCounter = 0;
    private string shownText;

    private void Start()
    {
        if (useThisText)
        {
            textToUse = GetComponent<Text>();
        }

        if (useTextText)
        {
            textToShow = textToUse.text;
        }

        if (useThisAudioSource)
        {
            audioSource = GetComponent<AudioSource>();
        }

        if (fade)
        {
            Fade();
        }
    }

    private IEnumerator FadeInText()
    {
        while (letterCounter < textToShow.Length)
        {
            if (colorFloat < 1.0f)
            {
                colorFloat += Time.deltaTime * fadeSpeedMultiplier;
                colorInt = (int)(Mathf.Lerp(0.0f, 1.0f, colorFloat) * 255.0f);

                textToUse.text = shownText + "<color=\"#FFFFFF" + string.Format("{0:X}", colorInt) + "\">" + textToShow[letterCounter] + "</color>";
            }
            else
            {
                colorFloat = 0.1f;
                shownText += textToShow[letterCounter];
                letterCounter++;

                if (playSound)
                {
                    audioSource.Play();
                }
            }

            yield return null;
        }
    }

    public void Fade()
    {
        StartCoroutine(FadeInText());
    }
}

 

Unity UI C# Fade In Text Letter By Letter With Sound
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504