Skip to content

Instantly share code, notes, and snippets.

@hyakugei
Created September 17, 2012 13:31
Show Gist options
  • Save hyakugei/3737274 to your computer and use it in GitHub Desktop.
Save hyakugei/3737274 to your computer and use it in GitHub Desktop.
Hacked "TextField" flow for ex2d's spriteFont
using UnityEngine;
using System.Text;
using System.Collections;
using System.Collections.Generic;
public class exTextLayout : MonoBehaviour {
public exSpriteFont textField;
public int textFieldWidth = 200;
public string textForField = "This is the default text.";
private static Dictionary<string, string> textCache;
void Start () {
textCache = new Dictionary<string, string>();
ReflowText(textForField);
}
public void ReflowText(string reflowText, bool useCache = true)
{
StartCoroutine(_ReflowTextTwo(reflowText, useCache));
}
private IEnumerator _ReflowTextTwo(string reflowText, bool useCache = true)
{
// check to see if we have this value already.
if(textCache.ContainsKey(reflowText) && useCache)
{
textField.text = textCache[reflowText];
yield break;
}
List<int> breakPoints = new List<int>();
textField.enabled = false;
textField.text = reflowText;
// we need a tick for the text field to update with the new text.
yield return null;
float tempWidth = 0;
Rect charRect;
int lastSpace = 0;
int i = 0;
while(i < reflowText.Length)
{
if(reflowText[i] == ' ')
{
lastSpace = i;
}
charRect = textField.GetCharRect(i);
tempWidth += charRect.width;
if(tempWidth >= textFieldWidth)
{
breakPoints.Add(lastSpace);
tempWidth = 0;
i = lastSpace + 1;
}
else
{
i++;
}
}
StringBuilder sb = new StringBuilder(reflowText);
foreach(int space in breakPoints)
{
sb.Replace(" ", "\n", space, 1);
}
// cache the reflowed text.
if(useCache) textCache[reflowText] = sb.ToString();
textField.text = sb.ToString();
textField.enabled = true;
}
}
@hyakugei
Copy link
Author

Made the text cache into a static class var. Also added the ability to bypass the cache.

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