+7 votes

How would you go about showing text on screen with an integer and string, ie: showing a stats/records screen where it says something like wins: 5 losses: 2?

I was guessing it would be something along the lines of:

extends Label
var x = 5
var y = 2
func _ready():
  set_text("wins: " + x + "Losses: " + y)

However, this doesn't seem to work.

Also, how would I go about adding a line, to get this:

Wins: 5
Losses: 2
in Engine by (25 points)
edited by

3 Answers

+15 votes

You can do that if you add str() to each of those variables to turn them into strings. You can also use a newline to add a line. The revised line would look like this: set_text("wins: " + str(x) + "\nLosses: " + str(y))

by (47 points)
+18 votes

You can also but everything into str()

label.set_text(str("wins: ", x , "Losses: ", y))
by (192 points)
BTW, I guess you meant "put" and not "but" :)
+6 votes

It is even more elegant to use format strings:

set_text("Wins: %d Losses: %d" % [x, y])

The benefit of using % from the start is that you could easily change the code later so that the output has more structured formatting. For instance, if you later want to give the literals a fixed width of 10 chars, you could use %10d.

by (38 points)

Definitely this. This is the entire purpose that format strings serve.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.