How can I get text value of TMPro Text without markup tags in Unity? - unity3d

I am trying to get text value in TMPro Text component without markup tags but haven't found any solutions.
Say, <b><color=red>Hello </color><b> world is the value in TMPro Text, and I just want Hello world in c# script.
Bear in mind that tag <b> and color will change, so I would love to remove tags dynamically, meaning I would like not to replacing each tag by text.replace("<b>", "") kind of things.
Does anyone know how to do it?

I dont know about the option of using HTML on tmp but you can attach the text to your script by create a new variable like that:
[SerializeField] TMP_Text textVar;
then you can drag you tmp game object to the component that include this script
and the you can change the text like that:
textVar.text = "what ever";
or get text like that:
string textString = textVar.text;
for the color you can use
Color color = textVar.color;

You can use TMP_Text.GetParsedText () to get the text after it has been parsed and rich text tags removed.
Alternatively you can also use regular expressions to search a string for rich text tags, and remove them while preserving the rest of the string.
using System.Text.RegularExpressions;
public static string GetString (string str)
{
Regex rich = new Regex (#"<[^>]*>");
if (rich.IsMatch (str))
{
str = rich.Replace (str, string.Empty);
}
return str;
}

Related

How to search for and highlight a substring in Codemirror 6?

I'm building a simple code editor to help children learn HTML. One feature I'm trying to add is that when users mouseover their rendered code (in an iframe), the corresponding HTML code in the editor is highlighted. So, for example, if a user mouses-over an image of kittens, the actual code, , would be highlighted in the editor.
Mousing-over the iframe to get the html source for that element is the easy part, which I've done (using document.elementFromPoint(e.clientX, e.clientY in the iframe itself, and posting that up to the parent) - so that's not the part I need help with. The part I can't figure out is how to search for and highlight that string of selected code in the code editor.
I'm using Codemirror 6 for this project, as it seems as it will give me the most flexibility to create such a feature. However, as a Codemirror 6 novice, I'm struggling with the documentation to find out where I should start. It seems like the steps I need to complete to accomplish this are:
Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"').
Highlight that range in the editor.
Can anyone out there give me some advice as to where in the Codemirror 6 API I should look to start implementing this? It seems like it should be easy, but my unfamiliarity with the Codemirror API and the terse documentation is making this difficult.
1. Search for a range in the editor's text that matches a string (ie.'<img src="kittens.gif"').
You can use SearchCursor class (iterator) to get the character's range where is located the DOM element in your editor.
// the import for SearchCursor class
import {SearchCursor} from "#codemirror/search"
// your editor's view
let main_view = new EditorView({ /* your code */ });
// will create a cursor based on the doc content and the DOM element as a string (outerHTML)
let cursor = new SearchCursor(main_view.state.doc, element.outerHTML);
// will search the first match of the string element.outerHTML in the editor view main_view.state.doc
cursor.next()
// display the range where is located your DOM element in your editor
console.log(cursor.value);
2. Highlight that range in the editor.
As described in the migration documentation here, marked text is replace by decoration. To highlight a range in the editor with codemirror 6, you need to create one decoration and apply it in a dispatch on your view. This decoration need to be provide by an extension that you add in the extensions of your editor view.
// the import for the 3 new classes
import {StateEffect, StateField} from "#codemirror/state"
import {Decoration} from "#codemirror/view"
// code mirror effect that you will use to define the effect you want (the decoration)
const highlight_effect = StateEffect.define();
// define a new field that will be attached to your view state as an extension, update will be called at each editor's change
const highlight_extension = StateField.define({
create() { return Decoration.none },
update(value, transaction) {
value = value.map(transaction.changes)
for (let effect of transaction.effects) {
if (effect.is(highlight_effect)) value = value.update({add: effect.value, sort: true})
}
return value
},
provide: f => EditorView.decorations.from(f)
});
// this is your decoration where you can define the change you want : a css class or directly css attributes
const highlight_decoration = Decoration.mark({
// attributes: {style: "background-color: red"}
class: 'red_back'
});
// your editor's view
let main_view = new EditorView({
extensions: [highlight_extension]
});
// this is where the change takes effect by the dispatch. The of method instanciate the effect. You need to put this code where you want the change to take place
main_view.dispatch({
effects: highlight_effect.of([highlight_decoration.range(cursor.value.from, cursor.value.to)])
});
Hope it will help you to implement what you want ;)
Have a look at #codemirror/search.
Specifically, the source code implementation of Selection Matching may be of use for you to adapt.
It uses Decoration.mark over a range of text.
You can use SearchCursor to iterate over ranges that match your pattern (or RegExpCursor)
Use getSearchCursor, something like this:
var cursor = cmEditor.getSearchCursor(keyword , CodeMirror.Pos(cmEditor.firstLine(), 0), {caseFold: true, multiline: true});
if(cursor.find(false)){ //move to that position.
cmEditor.setSelection(cursor.from(), cursor.to());
cmEditor.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
}
Programmatically search and select a keyword
Take a look at getSearchCursor source code it it give some glow about how it works and its usage.
So use getSearchCursor for finding text and optionally use markText for highlighting text because you can mark text with setSelection method of editor.
Selection Marking Demo
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
styleSelectedText: true
});
editor.markText({line: 6, ch: 26}, {line: 6, ch: 42}, {className: "styled-background"});
And it seem this is what you are looking for:
codemirror: search and highlight multipule words without dialog
RegExpCursor is another option that you can use:
new RegExpCursor(
text: Text,
query: string,
options⁠?: {ignoreCase⁠?: boolean},
from⁠?: number = 0,
to⁠?: number = text.length
)
Sample usage at:
Replacing text between dollar signs for Mathml expression.

TYPO3 using markers with conditions

There are some markers in my template. Sometimes markers can be empty, can I catch this situation? Something like:
if !###NEWS_IMAGE###
Markers or Subparts have no logic in the template.
All logic has to be done while generating the replacement text.
IN PHP you can use the usual PHP control structures.
if you fill the markers with Typoscript you can use the options of stdWrap.if to fill in any replacement string, even an empty string.
in this way you can condition label to show only if the value is set:
marks {
something = TEXT
something.field = title
something.wrap = the title is |
something.wrap.if.isTrue.field = title
something.ifEmpty = no title given
}

How to use different assets (audio, sprites and text) in Unity for different languages in a game?

I am developing a Unity 2D game where a user can select a language on the home screen and then the subsequent game should be played in the selected language itself. The language specific changes include audio files, sprites and text on Canvas UI elements. How can I approach this problem?
It depends a bit. There are different approaches for that.
I would probably do it with nested dictionaries and enums but there might be more elegant solutions.
Let's say you have a certain label for each text, sprite, sound, etc. in some enums like
enum TextLabel{
MainPanelTitle,
FireButton,
InfoText,
...
}
enum SpriteLabel{
LanguageFlag,
Background,
...
}
enum SoundLabel{
WelcomeMessage,
NationalHymn,
...
}
And for the language you would also have an enum like
enum Language{
English,
French,
German,
...
}
Than you would setup an individual dictionary for each language like
// Maps text labels to English texts
Dictionary<TextLabel,string> englishTexts;
// Maps text labels to french texts
Dictionary<TextLabel,string> frenchTexts;
// Maps text labels to German texts
Dictionary<TextLabel,string> germanTexts;
...
The same for Sprites (Dictionary<SpriteLabel,Sprite>) and Sounds (Dictionary<SoundLabel, AudioClip>)
You make like a main dictionary for each type for selecting the correct text/image/sound dictionary depending on the language:
Dictionary<Language, Dictionary<TextLabel,string>> texts;
Again the same with sprites and sounds.
Than at some point you have to fill the dictionaries. The texts (sounds, sprites) dictionary is the simplets one since it doesn't depend on external data:
texts = new Dictionary<Language, Dictionary<TextLabel,string>>(){
{Language.English, englishTexts},
{Language.French, frenchTexts},
{Language.German, germanTexts},
...
};
Well, now you "only" have to fill the information somehow into e.g. the text dictionaries. You can do this hardcoded in a script, drag/type in via the inspector or especially for texts e.g. use a .cvs table and parse that in during runtime. There are a lot of options for that step and it probably would fit for another question. In the end all will resume in some lines like
englishTexts[MainPanelTitle] = ...;
englishTexts[FireButton] = ...;
...
frenchTexts[MainPanelTitle] = ...;
...
Once e.g. the text dictionaries are filled with the information you can access a certain text (e.g. InfoText in French ) like
string infotext = texts[Language.French][TextLabel.InfoText];
As I said probably not the most elegant solution but that's how I would do it ;)
I do it before by this track
Var string Language;
Var UItext Title;
Then create buttons to choose language
in English button :
Language = “English”;
Then check what user choose
If (Language == “English”) {
Title = “Title Game” ;
}else if (Language == “Arabic”) {
Title = “عنوان اللعبة" ;
}

Code Mirror with Firebase mark text

I am trying to understand Code Mirror which I am using with FirePad - I get it all working, but now I want to do something a bit more 'exciting'.
I am looking to markText to make it readOnly but I cannot find out anywhere how to actually do it. My need is to load the editor, and preset with a template (best way to describe it) so that the template has some preset readOnly text and users then update the textarea after the read only text i.e. it can't be deleted/over written
Example (template being inserted into the FirePad):
<div><strong>Note</strong></div><br/>
<div>Type text in here</div><br/>
<div><strong>What has been achieved since last session</strong></div><br/>
<div>Type text in here</div><br/>
in this example people should be able to type in the area/s marked 'type text here'.
To call the text editor I use this:
var firepadRef = new Firebase('https://XXXXXXXXX.firebaseio.com/test');
var codeMirror = CodeMirror(document.getElementById('someID'), { lineWrapping: true });
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, { richTextToolbar: true, richTextShortcuts: true });
any ideas?

3DText - Change Text Through Script - Unity

I have read lot of questions on how to change text of a 3DText from script.
Lot of them suggested the following :::
GetComponent(TextMesh).text = "blah";
But when I try to use this, I get an error Expression denotes atype', where a variable',value' or method group' was expected
I tried a lot of examples and couldn't really get it to work.
TextMesh textMesh;
textMesh = (TextMesh) descriptionObject.transform.GetComponent("Text Mesh");
textMesh.text = "Name : ABC";
The above code though Compiles without errors doesn't change the text. Can someone help me out with this? How do I change the TEXT of a 3DText Object.
Thanks...
This would be a prettier solution than one already given(C# script used in example) :
//define a Textmesh that we want to edit
public TextMesh tm;
// here in start method (run at instantiating of script) i find component of type
// TextMesh ( <TextMesh> ) of object named"nameOfTheObject" and reference it
// via tm variable;
void Start () {
tm = (TextMesh)GameObject.Find ("nameOfTheObject").GetComponent<TextMesh>();
// here we change the value of displayed text
tm.text = "new Text u want to see";
}
Or if u want to do it the shortest way possible (syntax wise):
//keep in mind this requires for the script to be attached to the object u
// are editing (the 3dText);
//same as above, the only difference is the note in the line above as this
// method is run from gameObject.GetComponent....
// gameObject is a variable which would be equivalent of this.GetComp...
// in some other programming languages
GetComponent<TextMesh>().text ="new Text u want";
This Works !!!!
textMesh = (TextMesh) descriptionObject.transform.GetComponent(typeof(TextMesh));
textMesh.text = "Name : ABC";