Substitute values in an inspector string

Godot Version

4.4

Question

I am building character dialogs in the inspector using multiline @export variables. These strings sometimes include names that I would like to represent as a placeholder in the inspector and then have those placeholder values substituted with a value from a gdscript variable. So the player can use their name and then I don’t need to script every string n every dialog that mentions the player’s name. Thank you in advance!

Hi!

You could define an identifiable string, such as player_name, and replace that exact string with the player name. You could also use a formatting with brackets or something else, like [player_name], to identify quickly that this is a placeholder, that’s up to you.
Something like this:

var sentence: String = "player_name says hello!"
var playerName: String = "Robin"
var sentence_final: String = sentence.replace("player_name", playerName)
print(sentence_final)

# Output: Robin says hello!
1 Like

Try String’s .format

var input := "For you see {player}... it was me, {evil} all along!"
var format_data: Dictionary = {
    "player": "Skahtpin",
    "evil": "Dagoth Ur",
}
print(input.format(format_data))
1 Like

Thank you for the suggestions. They get me half way there. I wanted to be able to do it automatically from the inspector so my level designer didn’t need to work with the code. But I think if I add a setter to the @export var, I can do the substitution. I may need to write my own parser that checks what needs to be substituted in case there is nothing.

I use str() a lot in my debug statements as you can use it to build a string with variables fairly easily:

var value: int = 3

print(str("The value is ", value, "!"))