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 (113 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 (1,635 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 (272 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 (302 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 (5,651 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.