0
\$\begingroup\$

I am rading a text to be displayed in a Text UI from an asset using the standard commands

Resources.Load<TextAsset>("nameOfMyTextAsset");

The text is a .txt.

The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such.

I am using TextMesh Pro and insert the text via the following cmd

public TextAsset MainText;
MainText = Resources.Load<TextAsset>("nameOfMyTextAsset");
this.GetComponentInChildren<TextMeshProUGUI>().text = MainText.text;

The text is displayed like this

enter image description here

How can I read text with richtext tags from a text asset?

\$\endgroup\$
4
  • \$\begingroup\$ If you replace that last line with GetComponentInChildren<TextMeshProUGUI>().text = "<b>test string</b>" do you still see the tags? If not, then it's likely the brackets are getting escaped somehow. Walking through the string you get from MainText.text character-by-character, and reporting any character codes that shouldn't be there will help diagnose the issue. \$\endgroup\$
    – DMGregory
    Aug 5 '16 at 12:26
  • \$\begingroup\$ Excellent thought. I still do see the tags if I hardcode them though. \$\endgroup\$
    – JBJ
    Aug 5 '16 at 12:42
  • \$\begingroup\$ Then that means it's not the TextAsset source that's to blame. The TextMeshProUGUI component seems to not be using the tags it's given via the text property. Does the component expose a flag to enable rich text, or a SetRichText method? (I'm having trouble finding the documentation for this 3rd party component) \$\endgroup\$
    – DMGregory
    Aug 5 '16 at 12:56
  • \$\begingroup\$ Thanks! The curious thing is: If I enter tags into the text input box -- directly within the Text Mesh Pro GUI entering the text in the inspector -- then on play the text gets rendered correctly. Side note: yes, the GUI has a toggle to "Override Tags", which I disabled course. \$\endgroup\$
    – JBJ
    Aug 5 '16 at 13:25
1
\$\begingroup\$

Here we go, thanks for the hint, @DMGregory. By trial and error:

One has to enable rich text before assigning the text to the object. The full commands would be

using UnityEngine;
using System.Collections;
using TMPro;

public TextAsset MainText;

// put this in some function
MainText = Resources.Load<TextAsset>("nameOfMyTextAsset");
// enable rich text
this.GetComponentInChildren<TextMeshProUGUI>().richText = true;
this.GetComponentInChildren<TextMeshProUGUI>().text = MainText.text;
\$\endgroup\$
1
  • \$\begingroup\$ Consider caching a reference to the TextMeshProUGUI component, rather than incurring the search cost of GetComponentInChildren multiple times. \$\endgroup\$
    – DMGregory
    Aug 5 '16 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.