Skip to content

Instantly share code, notes, and snippets.

@korbul
Last active October 31, 2017 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save korbul/b8fc9dcbc97e7f015955be066cd254b9 to your computer and use it in GitHub Desktop.
Save korbul/b8fc9dcbc97e7f015955be066cd254b9 to your computer and use it in GitHub Desktop.
Unity extension to visually transform a text into another over time.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public static class TextScrambler {
/// <summary>
/// Transition from one text to another over time
/// </summary>
/// <param name="monoBehaviour"></param>
/// <param name="initial">text to transition from</param>
/// <param name="final">text to transition to</param>
/// <param name="time">time in seconds to transition</param>
/// <param name="assignFunction">assign the output to your text. example: (result)=>{myText.text = result;}</param>
public static void Scramble(this MonoBehaviour monoBehaviour, string initial, string final, float time, Action<string> assignFunction)
{
monoBehaviour.StartCoroutine(ScrambleCoroutine(initial, final, time, assignFunction));
}
private static IEnumerator ScrambleCoroutine(string initial, string final, float time, Action<string> assignFunction)
{
string bigger = initial.Length > final.Length ? initial : final;
var waitTime = new WaitForSeconds(time / bigger.Length);
List<int> positions = new List<int>(bigger.Length);
for (int i = 0; i < bigger.Length; i++)
{
positions.Add(i);
}
StringBuilder stringBuilderInitial = new StringBuilder(initial);
while(positions.Count > 0)
{
int posIdx = UnityEngine.Random.Range(0, positions.Count);
int pos = positions[posIdx];
if(pos < stringBuilderInitial.Length)
{
if(pos < final.Length)
{
stringBuilderInitial[pos] = final[pos];
}
else
{
stringBuilderInitial.Remove(pos, 1);
if(posIdx < positions.Count - 1)
{
for (int i = posIdx + 1; i < positions.Count; i++)
{
positions[i]--;
}
}
}
}
else
{
stringBuilderInitial.Append(' ', pos + 1 - stringBuilderInitial.Length);
stringBuilderInitial[pos] = final[pos];
}
positions.RemoveAt(posIdx);
assignFunction(stringBuilderInitial.ToString());
yield return waitTime;
}
}
}
@korbul
Copy link
Author

korbul commented Oct 30, 2017

This is a MonoBehaviour extension. It has to be used from a MonoBehaviour inheriting class since it's using coroutines to achieve the effect.
Usage example:

void Start()
{
    this.Scramble("hello", "world", 1, (result) => { guiText.text = result; });
}

demo:
scramble gif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment