The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes

Noob question but is there a better way to excute a block of code for once than this:

var do-once=true

func process():
if do-once:

Godot version 3.4
in Engine by (204 points)

4 Answers

+2 votes
Best answer

If your concern is that you have too many booleans then another option is a dictionary with key value pairs which do the same thing for instance;

var booleans_dict = {"key1": false, "key2: false, "key3": false}

change the key1 etc to words which mean something in your code and you can access them like this

func process():
    if booleans_dict["key1"] == false:
        do your stuff here
        booleans_dict["key1"] = true

or you could use 0 and 1 rather than true and false if you wanted.

by (3,328 points)
selected by
+1 vote

There are other ways for sure, though not necessarily better.

A boolean guard like you have is perfectly fine for most cases, though note that it is not thread-safe. But unless you're working with threads you don't have to worry about that.

by (288 points)

thanks, the problem is in this way i have millions of variables at the start of script.

Can you provide more context on how you're using these guards? What type of functionality are you trying to achieve?

Rather than examining options for guarding a single method I get the feeling the question should be more about structuring your project to avoid the use of many single-shot blocks of code.

0 votes

Not to mention something obvious, but if you only want something to run once, don't run it in process. Process runs every frame. Instead, put what you want to do in a function and run that when you need it to.

by (562 points)
+1 vote

Turn attention to signals and setget. These are two good general ways to design code running limited and controlled amount of times

by (8,188 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 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.