C# script for Unity UI text to make retro shifting text effect.

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

// © 2017 TheFlyingKeyboard 
// theflyingkeyboard.net 

public class MovingText : MonoBehaviour {
  [SerializeField] private Text textToUse;
  [SerializeField] private bool useThisText = false;
  [SerializeField] private string textToShow;
  [SerializeField] private bool useTextText = false;
  [SerializeField] private bool moveRight = false;

  [SerializeField] private float timeBetweenChanges = 1.0f;
  [SerializeField] private bool moveOnStart = false;

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

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

    if (moveOnStart)
    {
            StartMoving(textToUse, textToShow, timeBetweenChanges);
    }
  }

  private IEnumerator MoveText(Text newText, string message, float timeToChange)
  {
    while (true)
    {
      if (moveRight)
      {
                message = message.Substring(message.Length - 1, 1) + message.Substring(0, message.Length - 1);
      }
      else
      {
                message = message.Substring(1, message.Length - 1) + message.Substring(0, 1);
      }

            newText.text = message;

      yield return 0;
      yield return new WaitForSeconds(timeToChange);
    }
  }

    public void StartMoving(Text newText = null, string message = null, float timeToChange = -1.0f)
    {
        if (newText != null && message != null && timeToChange > 0.0f)
        {
            StartCoroutine(MoveText(newText, message, timeToChange));
        }
        else if (newText != null && message != null)
        {
            StartCoroutine(MoveText(newText, message, timeBetweenChanges));
        }
        else if (message != null && timeToChange > 0.0f)
        {
            StartCoroutine(MoveText(textToUse, message, timeToChange));
        }
        else if (newText != null && timeToChange > 0.0f)
        {
            StartCoroutine(MoveText(newText, textToShow, timeToChange));
        }
        else if (newText != null)
        {
            StartCoroutine(MoveText(newText, textToShow, timeBetweenChanges));
        }
        else if (message != null)
        {
            StartCoroutine(MoveText(textToUse, message, timeBetweenChanges));
        }
        else if (timeToChange > 0.0f)
        {
            StartCoroutine(MoveText(textToUse, textToShow, timeToChange));
        }
    }

    public void StopMoving()
    {
        StartCoroutine(MoveText(textToUse, textToShow, timeBetweenChanges));
    }
}

 

Unity UI C# Shifting Text Effect
Tagged on:         

Leave a Reply

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