Willien
Willien

Reputation: 75

Global variable not being updated outside the global script

Yes the ball is entering (and leaving) the area2D when i start the game

Yes global.gd is a autoloaded script

In global i have a big area2d that detect if a body have entered. var chase_ball inside the global are being updated but in the Global.chase_ball its always false (the default value)

Originally the area2D was inside the enemy node but i wanna the area2D to be fixed in the main scene, not moving together with the enemy

global.gd:

extends Node2D

var chase_ball = false

func _process(delta):
        print(chase_ball)

func _on_ball_detector_body_entered(body):
    chase_ball = true

func _on_ball_detector_body_exited(body):
    chase_ball = false

output:

true
false
true
false
(same loop as above)

enemy.gd:

func _process(delta):
    print(Global.chase_ball)

output:

false
false
false
false
(same loop as above)

The expeted result is to Global.chase_ball update acordly to the func _on_ball_detector_body_entered/exited(body):

Upvotes: 0

Views: 514

Answers (1)

Theraot
Theraot

Reputation: 40295

If you are autoloading global.gd, then the Editor is not connecting the methods to the signals.

Yes, you have methods that match the signals, and you probably created them by connecting them... But the connection is not part of the script. Instead it is saved alongside the Node (i.e. it saved in a scene).

So when you autoload said script, Godot will create a new Node for it, and it does not have the connections.


Now, you say you want the Area2D - which would be emitting the signals - to be on your main scnee. So the path of least resistance would be to:

  • Have a script on the Area2D itself.

    extends Area2D
    
  • Connect the signals of the Area2D to itself using the editor, so there are methods for them in this new script.

    extends Area2D
    
    func _on_body_entered(body: Node2D)  -> void:
        pass
    
    func _on_body_exited(body: Node2D) -> void:
        pass
    
  • And from those mehtod call the global.

    extends Area2D
    
    func _on_body_entered(body: Node2D)  -> void:
        Global._on_ball_detector_body_entered(body)
    
    func _on_body_exited(body: Node2D) -> void:
        Global._on_ball_detector_body_exited(body)
    

    Of course, at that point, you do not need to have those methods in global.gd, you can remove them and access chase_ball directly:

    extends Area2D
    
    func _on_body_entered(body: Node2D)  -> void:
        Global.chase_ball = true
    
    func _on_body_exited(body: Node2D) -> void:
        Global.chase_ball = false
    

Upvotes: 1

Related Questions