I'm looking for more efficient way to randomly swap a long list of messages

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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():
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”

:bust_in_silhouette: Reply From: jgodfrey

Sure - just place all of your messages in a single array and then randomly select an index into that array to pick a message. So, something like this:

var msgs = []
msgs.append("Message #1")
msgs.append("Message #2")
msgs.append("Message #3")
msgs.append("Message #4")
var msg = msgs[randi() % msgs.size()]

Thank you so much. I’m new to this type of programming so it really helps when I can see how to do something. Much appreciated.

dondudding | 2020-01-27 22:19