Changing a script's variables not working

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

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 == "Player"
      if stats.coin_count < 100 and visible:
         stats.coin_count += 1

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 := 

Does coin_count 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 coin_count?

SteveSmith | 2022-11-26 14:21

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.

scopericrit | 2022-11-26 22:00

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 coin_count before and after “stats.coin_count += 1” to see what the value is?

SteveSmith | 2022-11-27 11:15

:bust_in_silhouette: Reply From: SnapCracklins

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).

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 := 

scopericrit | 2022-11-26 21:44

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

SnapCracklins | 2022-11-26 22:06

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

scopericrit | 2022-11-26 22:26