Hello a little problem with chanchanging the scene

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By feiuwgfwoief

so I made the code in the coin scene where ur characters collect all coins all 15 coins(maxcoins) it’s gonna change the scene but it didn’t work until i change the max coin to 1 it work but more than that it doesn’t work

enter code here

extends Area2D

var collectedCoins = 0
var maxCoins = 2

func _on_body_entered(body):
if body.name == “Player”:
var tween = get_tree().create_tween()
var tween1 = get_tree().create_tween()
tween.tween_property(self, “position”, position - Vector2(0, 35), 0.35)
tween1.tween_property(self, “modulate:a”, 0, 0.3)
tween.tween_callback(queue_free)

	collectedCoins += 1
	print("Collected coins:", collectedCoins)  
	
	if collectedCoins >= maxCoins:
		print("Reached maximum coins!")
		get_tree().change_scene_to_file("res://main.tscn")
:bust_in_silhouette: Reply From: Vadalken

Each coin scene is independent. So every coin scene you make has it’s own variable for collectedCoins and maxCoins. None of the coins know about any of the other coins, so they only count when they themselves are picked up.

There are a few ways I would consider dealing with this:

  1. An easy but bad practice solution is to count the coins with a global variable.
  2. If you want to migrate to (or already use) Godot 4.1 you can use a static variable that will be shared between all class instances. This is pretty much what you are currently trying to do, but is only available in Godot 4.1 that was released 2 days ago.
  3. Emit a signal when a coin is collected and use it to count coin collection further up the scene tree. I would prefer if the node counting the coins has all the coins bellow it in the scene tree, but this is not strictly necessary.
  4. Have the character keep track of the coins. There are many ways of doing this.

you could also simply use a const var.