The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

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 onbodyentered(body):
if body.name == "Player":
var tween = get
tree().createtween()
var tween1 = get
tree().createtween()
tween.tween
property(self, "position", position - Vector2(0, 35), 0.35)
tween1.tweenproperty(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")
in Engine by (12 points)

1 Answer

0 votes

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.
by (197 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 Frequently asked questions and 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 [email protected] with your username.