Displaying Dynamic Variables Inside RichTextLabel

Godot Version



Hey folks, here with a question.
I am trying to make a game that is text based, and uses a lot of global variables to display things that the player has. What I am trying to do is insert these variables into a richtextlabel, and I was wondering if anyone has any experience with this?

Currently the way i am doing this is as follows:

@onready var textBox = $"RichTextLabel"

"You ready your " + str(Global.playerWeaponStatus) + str(Global.playerWeapon) + " and face the skeleton!")

This code would end up with a sentence that reads: “You ready your rusty sword and face the skeleton!”
As you can see, adding in variables isn’t that difficult, it is just clunky and messy in my opinion.
It gets even more messy if you have an array of possible variables that you want to inject randomly!
To do that, I had to make a function that when called selects a random element in the array:

var playerWeaponStatus= ["rusty", "damaged"]
func playerWeaponStatusRandom():
	var RandomIndex = randi_range(0, playerWeaponStatus.size() - 1)
	return playerWeaponStatusRandom[RandomIndex]

After this function is declared in the Global script, I could then call it when generating the richtextlabel:

textBox.parse_bbcode("You ready your ")
text = Global.playerWeaponStatusRandom()
textBox.append_text(str(Global.playerWeapon) + " and face the skeleton!")

This code would end up with a sentence that reads: “You ready your rusty sword and face the skeleton!”
Or it would read: “You ready your damaged sword and face the skeleton!”
Either options could populate thanks to the random function.

Once again, very clunky IMO, and very unwieldy when trying to make a long sequence of text that has numerous variables and randomly selected elements added.

If anyone has any insights on how I could streamline the injection of these variables and random elements into the text I would greatly appreciate it!

Instead of playerWeaponStatusRandom you can simply call playerWeaponStatus.pick_random(). pick_random is a function of array.

I think it could be fun to randomize the words before the weapon too. You could have var prefix: Array = [“you ready your weapon”, “hesitantly, you draw your”]. If you can separate these combination of words into categories, you can select from there.

I think your current approach is fine. You could also create functions for certain actions that will take the relevant parameters and pick the right words.
func face_enemy(weapon: String, enemy: String):
textBox.append_text(prefix.pick_random() + weapon + suffix.pick_random() + enemy)

1 Like

Thank you for the response! I had no idea you could use .pick_random() to grab random elements from an array, so that will help immensely!

1 Like