Skip to content

Instantly share code, notes, and snippets.

@renaudbedard
Created September 17, 2014 04:16
Show Gist options
  • Select an option

  • Save renaudbedard/71b80bd7d76e4967376c to your computer and use it in GitHub Desktop.

Select an option

Save renaudbedard/71b80bd7d76e4967376c to your computer and use it in GitHub Desktop.
Barely tested Unity "Rich Text" substring tool
struct SubstringInfo
{
public int StartsAt;
public string TagSuffix;
public SubstringInfo(int startsAt, IEnumerable<string> tagSuffixChain)
{
StartsAt = startsAt;
TagSuffix = string.Empty;
foreach (var tagSuffix in tagSuffixChain)
TagSuffix += tagSuffix;
}
}
SubstringInfo[] textLengthFor;
// --------
// get text lengths
var textLengths = new List<SubstringInfo>();
var fullText = TextResource.text;
var tagStack = new Stack<string>();
int tentativeTagStartAt = -1;
for (int i = 0; i < fullText.Length; i++)
{
char at = fullText[i];
if (at == '<')
{
if (tentativeTagStartAt != -1)
// wasn't a tag, add characters from there to here
for (int j = tentativeTagStartAt; j < i; j++)
textLengths.Add(new SubstringInfo(j, tagStack.ToArray()));
tentativeTagStartAt = i;
}
else if (at == '>')
{
if (tentativeTagStartAt != -1)
{
var tag = fullText.Substring(tentativeTagStartAt, i - tentativeTagStartAt);
if (tag.StartsWith("<color"))
tagStack.Push("</color>");
else if (tag.StartsWith("<size"))
tagStack.Push("</size>");
else if (tag.StartsWith("</color") || tag.StartsWith("</size"))
tagStack.Pop(); // assume they'll match...
else
{
// unrecognized tag, parse as text
for (int j = tentativeTagStartAt; j < fullText.Length; j++)
textLengths.Add(new SubstringInfo(j, tagStack.ToArray()));
}
tentativeTagStartAt = -1;
}
else
textLengths.Add(new SubstringInfo(i, tagStack.ToArray()));
}
else
{
if (tentativeTagStartAt == -1)
textLengths.Add(new SubstringInfo(i, tagStack.ToArray()));
}
}
if (tentativeTagStartAt != -1)
// wasn't a tag, add characters from there to here
for (int j = tentativeTagStartAt; j < fullText.Length; j++)
textLengths.Add(new SubstringInfo(j, tagStack.ToArray()));
// --------
// usage
guiText.text = fullText.Substring(0, textLengthFor[shownCharCount].StartsAt) + textLengthFor[shownCharCount].TagSuffix;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment