0 votes

I have an array and a variable which is:

var steps = [ step1(), step2(), step3() ]
var currentStep = 0

and have some functions that goes like:

func _input(event):

if event.isactionpressed("ui_accept"):

executeStep()

func executeStep():

steps[currentStep]
currentStep += 1

func nextStep():

currentStep += 1

My problem is when I start the game it triggers all 3 steps even before I click anything(for now steps only prints numbers in command). I thinks it's because of the way I wrote the array cause tried to CTRL + K everything else but it still was the same. Is there a way to do this other that 100 if else statements?

Godot version latest
in Engine by (70 points)

1 Answer

+2 votes

Option 1: Use match

Instead of too much if elif else we can try using match.

func executeStep():
    match currentStep:
        0:
            step1()
        1:
            step2()
        2:
            step3()
    currentStep += 1

If you go with this option then you won't need the steps array anymore.

Option 2: Use Callables

We can use a Callable to store a function, and then we can call the function any time we want (as many times as we want).

var steps = [Callable(self, "step1"), Callable(self, "step2"), Callable(self, "step3")]
var currentStep = 0

func executeStep():
    steps[currentStep].call()
    currentStep += 1

If we need to pass in arguments we go steps[currentStep].call(arg1, arg2, arg3), where for example I passed in three arguments.

by (180 points)

As an addendum I will show a way to avoid typing Callable 100 times, if there are 100 steps.

const numberOfSteps = 100
var steps = []
var currentStep = 0

func _ready():
    for i in range(numberOfSteps):
        var functionName = "step" + str(i + 1)
        var callable = Callable(self, functionName)
        steps.append(callable)

Thank you god sir for sparing some time and helping me

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 Frequently asked questions and 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 [email protected] with your username.