How do I change a number to a random number every 10 seconds?

Godot Version

4.6.1

Question

I have these script-wide variables named rng and number. What I want to do is make the number change every 10 seconds without making them local. How do I accomplish this?

var rng = RandomNumberGenerator.new()
var number = rng.randi_range(0, 100)

Create a Timer, set it to 10 seconds and have it not a one-shot. Then have it change the number every time it times out.

They are being used in a Singleton or Autoload.

When putting a variable in a function or in a statement, it is local; you can’t use it anywhere else except in that if statement or function.

func local():
    var local = true

A script-wide variable can be accessed anywhere in the script like this:

extends Node

var script_wide = true

func script_wide():
    if script_wide:
       print(script_wide)

Or at least that’s what I was told they’re called.

Oh yeah, I totally misunderstood. “script-wide” isn’t a thing. Though it’s a valid description.

What you are talking about is Scope. In this case, you have a class-scoped variable and are calling it “script-wide”. A “local” variable is one that is local to its scope and does not exist outside it. So a class-scoped (“script-wide”) variable is local to the class, or entire script.

Scope is determined based on where the variable is declared.

4 Likes

Ah, okay.

No, that’s different. Private variables are prepended with an underscore by convention in GDScript, but there’s no such thing as access modifiers (public, private, protected) in GDScript. Everything is technically public all the time.

2 Likes

I understand the timer part, but I tried reading the docs but found nothing for “re-randomizing” the numbers.

Just do this again:

number = rng.randi_range(0, 100)

Once it’s declared at the class level scope, you can modify it inside a function.

1 Like

Making a variable inside a loop is scope, not access modifier. It’s not private, it just gets deleted once the loop is done, and therefore doesn’t exist outside it.

Again, you’re describing scope, not access modifiers.

2 Likes

Just to quickly prove your point, you can see the “scope” buzzword mentioned by the IDE itself with this simple example:

3 Likes