BBCode on rich text label string length

Godot Version

4.2

Question

my dialogue system has implemented a type writter effect as follows:

	if on_auto:
		self.visible_ratio += ((data.auto_play_speed * delta * play_speed_factor)
		/self.text.length())
	else:
		self.visible_ratio += ((data.play_speed * delta * play_speed_factor)
		/self.text.length())

data.auto_play_speed and play_speed_factor are 2 export constants
I recently switch from label to rich text label so BBcode can be used on my dialogue.
However, when displaying text with small length, the speed tends to be extremely slow.
I presume the issue is with that BBcode are count as length of the text but not displayed. Thus shorter text with BBcode as a greater percentage of text length gets “typed” slower.
Is there a shortcut to count length of string without BBcode (especially with multiple of them in text) or do I have to deal with regrex again.

I think with the .length() scheme you’re using, it won’t separate out control codes, so if you have (say):

[p][color=red]hi[/color][/p]

The length() of that will be 28, but there are only 2 characters that will actually draw, so I’d imagine you’d get a lot of dead time; in this case your code would play it back at 2/28 speed (that is, 14 times as long as you expect).

The docs say that when you set visible_ratio it sets visible_characters and vice versa; by default visible_characters is -1, which means “show everything” without having to know what the number of visible characters would be, but setting visible_ratio to other values should set visible_characters.

If you’re really lucky, explicitly setting visible_ratio to 1.0 will actually calculate visible_characters for you, and you’ll be able to cache that number and use it. If you’re slightly less lucky and it’s checking to see if the value has changed, you might have to set it to (say) 0.5 first and then 1.0 to force the calculation.

If you’re significantly less lucky and setting 1.0 gives you -1 for visible_characters, you might have to do shenanigans with nearly-one values; set a value of 0.999999999 for visible_ratio and unless you have a vast amount of text, that should effectively be all the characters (or possibly one less than, depending on rounding…).

At worst, you could binary search over visible_ratio settings to get the largest value that isn’t -1, though that’s something you’d really want to do once rather than every update.

Is there a shortcut to count length of string without BBcode

RichTextLabel has a function called get_parsed_text() that returns its text without the BBCode, so get_parsed_text().length() should do what you need in this case.

2 Likes

works! ty!