UnityGameProjectsCode / NightwatchGame / InteractionTextControl.cs
InteractionTextControl.cs
Raw
using System.Collections;
using TMPro;
using UnityEngine;

public class InteractionTextControl : MonoBehaviour
{
    private TextMeshProUGUI interactionText;
    private Animator animControl;
    private AudioSource tickAudio;
    private bool removingText;
    public float removalSpeed;
    public float waitTimeBeforeRemovalStart;
    private bool overTimeActive;

    private void Awake()
    {
        interactionText = GetComponent<TextMeshProUGUI>();
        animControl = GetComponent<Animator>();
        tickAudio = GetComponent<AudioSource>();
    }

    private void FixedUpdate()
    {
        if (removingText)
        {
            if (interactionText.text.Length == 0)
            {
                removingText = false;
                return;
            }

            if (!overTimeActive)
                StartCoroutine(RemoveTextOverTime());
        }
    }

    public void DisplayText(string newContent)
    {
        interactionText.text = newContent;
        animControl.Play("Text Fade In", 0, 0);

        StopAllCoroutines();
        removingText = false;
        overTimeActive = false;

        StartCoroutine(WaitToStartRemoving());
    }

    public IEnumerator RemoveTextOverTime()
    {
        overTimeActive = true;

        yield return new WaitForSeconds(removalSpeed);

        string textCopy = interactionText.text;

        textCopy = textCopy.Substring(0, textCopy.Length - 1);

        interactionText.text = textCopy;

        tickAudio.Play();

        overTimeActive = false;
    }

    public IEnumerator WaitToStartRemoving()
    {
        yield return new WaitForSeconds(waitTimeBeforeRemovalStart);

        removingText = true;
    }
}