0 votes

I have an array:

array = ["option1", "option2", "option3"]
var selected_option

I have function assigned on an Input event:

func _input(event): 
if event is InputEventKey:
if event.is_action_pressed("select_option"):
selected_option = array[randi() % array.size()]

And then I want to execute different functions based on the selected option:

func execute_option():
if selected_option =="option1": play_option1()
if selected_option == "option2": play_option2()
if selected_option == "option3": play_option3()

func play_option1(): print("Option 1 is selected")
func play_option2(): print("Option 2 is selected")
func play_option3(): print("Option 3 is selected")

So what I want to ask is that is there another less complicated way to do this. The reason I don't just print at the first function is that I want to do more with each option than just printing.

in Engine by (19 points)

2 Answers

0 votes
Best answer

Firstly a less complicated way is to use one function passing in different params

func execute_option(option):
    match option:
        "option1": 
            print("Option 1 is selected")
            # do other option 1 stuff
        "option2": 
            print("Option 2 is selected")
            # do other option 2 stuff
        "option3": 
            print("Option 3 is selected")
            # do other option 3 stuff

Answering your question as is, you can use the call method however your functions must have the same name as the options

var array = ["option1", "option2", "option3"]

func _input(event): 
    if event is InputEventKey:
        if event.is_action_pressed("select_option"):
            var option = array[randi() % array.size()]
            call(option)

func option1(): print("Option 1 is selected")
func option2(): print("Option 2 is selected")
func option3(): print("Option 3 is selected")
by (4,972 points)
selected by

Ok thank you, the call method works wonderfully.

0 votes

If you can make it so your array contains the names of your functions as a string you can just do:

array.shuffle()
call(array.front())

Otherwise the only way you can clean it up a little is by using a match statement instead of the ifs.

by (3,707 points)
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.