Created
September 17, 2014 04:16
-
-
Save renaudbedard/71b80bd7d76e4967376c to your computer and use it in GitHub Desktop.
Barely tested Unity "Rich Text" substring tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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