Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | dondudding |
I’m using a button to change the text in a label to a different random message every time the button is clicked. The GD code I’m using is working fine, but it feels clunky because I am a newbie who is still trying to figure out the best way to do things. There must be a more elegant way to do this than have a long series of elif statements. In the example below (the code I’m using now), I have it set up to randomly use one of six messages as the label text, but in my final project, I am expecting to have over 50 messages and so 100 lines of "if var whichmessage == 35: var message = “Message Thirty-Six” feels like a novice way of getting this done. Is there a way I can put all of my messages into something like an array and use only one or two elif statements? There’s going to be a lot of times in the project I’m working on where I will need to pull randomly from a pile of 50 or more objects so if I can get this figured out now, it’s going to save me some trouble down the road. Thanks for whatever advice I can get on this.
extends Button
var whichmessage = 0
var message = “First Message”
var x = 0
func _randomize_my_variable():
x = randi()%6
func _on_Screen1Button_button_up():
_randomize_my_variable()
whichmessage = x
get_parent().get_node(“Messagebox1”).text = message
if whichmessage == 1:
message = “Second Message”
elif whichmessage == 2:
message = “Third Message”
elif whichmessage == 3:
message = “Fourth Message”
elif whichmessage == 4:
message = “Fifth Message”
elif whichmessage == 5:
message = “Sixth Message”