0 votes

I have a script containing the game's stats and an coin Area2D increasing one of the stats when collected. The problem is the coin count stat doesn't increase when the coin is collected.

The game stats:

class_name Stats
extends Resource

export(int, 0, 100) var coin_count

The coin Area2D:

extends Area2D

func _on_Coin_body_entered(body):
   if body.name == "Player"
      if stats.coin_count < 100 and visible:
         stats.coin_count += 1
         queue_free()

Some things I want to address:
1. The if conditions for the coin collection does work since the coin disappear when the Player enter the coin area
2. The stats' coin count still not change from the remote tab
3. For the coins, the coin counts do increase, but the script's stats don't as if it was unaffected. It's likely this part of code who is the culprit

var stats := Stats.new() 
Godot version 3.4
in Engine by (21 points)
edited by

Does coincount need to be an export? What is the parent of stats, or is it global? Is stats visible? Have you tried putting a breakpoint on the line that increments the coincount?

If you meant the owner of the stats, the stats have none.
The tutorial I saw about saving progress did make it exports, but its still not work in basic var.

Stats must be "owned" by something, otherwise that might be your problem, in that it's being recreated each time. Everything has an owner (apart from the top level scene) or else it will be GC'd. Also, have you tried print()-ing coincount before and after "stats.coincount += 1" to see what the value is?

1 Answer

–1 vote

You are freeing the object at the same time you update the variable so it likely releases itself before the variable can change. You need to sequence it. Make something like a "fading" animation for your coin, still have the change at pickup, but don't queue_free until the signal at the end of the animation (you should be able to connect it in the editor).

by (534 points)

Nope, doesn't work. But I realized that for the coins, the count did go up but the script's stats are still zero as if it was unaffected. Its likely this part of code who is the culprit

var stats := Stats.new() 

Ah - I see. Are you using any global variables for stats by chance?

If you meant autoload, no
If you meant being turn into a variable by all other scripts, yes

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.