How to make variables update across all instances of a scene

Godot Version

Question

I’m making a flappy bird game in Godot and I’m trying to implement a score system. I want to change a “score” variable every time the player goes through a set of pipes, but since I am instantiating the pipe scene, every set of pipes has their own independent variable. Is there a way I can make them share and update one instead?

Here is the code for the pipes (relevant part is at the bottom

extends Node2D

@export var move_speed = 300
var game_over = false
var score = 0

func _ready():
	# Connecting to the signal when a pillar spawns
	var pillar_spawn = get_node("/root/Game/PillarSpawn")
	pillar_spawn.timeout.connect(_on_pillar_spawn_timeout)

func _physics_process(delta):
	# Moving pillars to the left
	global_position.x -= move_speed * delta 
	
	# Deleting pillars when exiting the screen
	if global_position.x < -100:
		queue_free()
		print("Pillar deleted")

# Connecting to game_over signal in all killzones
func _on_pillar_spawn_timeout():
	var kill_zone = get_tree().get_nodes_in_group("KillZones")
	for KillZone in kill_zone:
		KillZone.body_entered.connect(_on_kill_zone_body_entered)

# Changes game_over variable to true
func _on_kill_zone_body_entered(body):
	game_over = true


func _on_score_area_body_entered(body):
	if game_over == false:
		score += 1
		print(score)

And here is the code where i instantiate them

extends Node2D
signal pillar_spawned

func _ready():
	Engine.time_scale = 1

func _on_pillar_spawn_timeout():
	# Spawning pillars in the correct location
	var new_pillars = preload("res://scenes/pillars.tscn").instantiate()
	new_pillars.global_position.x = 1550 # Set x koordinate
	new_pillars.global_position.y = randf_range(650, 350) # Randomize y coordinate
	add_child(new_pillars) # Place the pillars
	print("Pillar spawned")

#Speeding up game over time
func _on_speed_up_game_timeout():
	Engine.time_scale += 0.01

You can put the score in the pipe’s parent and change the code in the pipe to be something like:

func _on_score_area_body_entered(body):
	if game_over == false:
		get_parent().score += 1 # changing score to get_parent().score
		print(get_parent().score)
1 Like

Singletons or static variables are nice for something like that.
https://youtu.be/jQvcTiVwUgw?si=EhenIAoGOCfCNmKW

1 Like

Having a score variable on the obstacles doesn’t make much sense. Move the score onto the player - or better yet, have a global singleton that keeps track of that score. That way when the game ends, you still have the score somewhere safe and you can display it on the game over screen.

I’d say create a ScoreManager autoload and have the variable there. And reset it to 0 when a new game starts.

1 Like

Thanks, very useful!

1 Like

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