How to use static variables?

Godot Version 4.2.1

I have no idea how to use static variable.

When I use static variable it is always null.

@suredesm I would say that the official explanation is pretty straightforward: GDScript reference — Godot Engine (stable) documentation in English

Which part doesn’t work for you?

Dobry den, mozem Vas aj ja poprosit o radu?

Thank you for your support.

class_name Foo extends Object

static var count = 0

# This function get called multiple times (like thousands)
# So to avoid multiple prints (which takes enormous amount of time) and
# print single time to make sure this function is called
func bar():
    if count == 0:
        print("This code got called!")
        count = 1


This printed nothing. So I just printed count.

class_name Foo extends Object

static var count = 0

func bar():
    print(count)

This just prints <null>. I don’t know what did gone wrong.

Thank you for the reply but I don’t understand.

1 Like

How do you call the function bar()? Since it is an instance function (there is no static in the declaration), I suppose you create an instance of the class Foo first?

Yes, I create an instance and call that bar(). This bar() function defiantly get called I have no doubt about that but this static variable count is even though it is initialized.

I can’t repeat this no matter what I try.

Are you giving us everything you are doing?

Try this on an empty project.

1 Like

Put your entire project to GitHub and we’ll see. I have no issues with static variables.

1 Like

It seems working on other circumstances. And this is not wanted me for now because I used it as debugging. Thank you for your time sir. Much appreciated.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.