Access variable from other script using signal

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

I have this function that should emit a signal, but my signal does not seem to be working as I expected. It does everything inside that function hit_bottom()…

extends Area2D

signal recharge

func _ready():
	pass # Replace with function body.

func hit_bottom(node):
	$"../../shoot".position = node.position

… but the other script does not run the function associated with that signal emitted.

extends KinematicBody2D

var ball = preload("res://scenes/ball.tscn")
var velocity = Vector2()
export (int) var cartridge = 50
var initial_pos = Vector2()
var wait = true

func _ready():
	self.connect("recharge" , self , "on_recharge")
func get_input():
	velocity = Vector2()
	if Input.is_action_just_pressed("ui_shoot"):
		wait = false
		initial_pos = get_global_mouse_position() - $muzzle.global_position

func shoot():
	if cartridge > 0:
		var b = ball.instance()
		var g = get_tree().get_nodes_in_group("balls")
		var dir = initial_pos
		if dir.length() > 5:
			rotation = dir.angle()
			velocity = move_and_slide(velocity)
		b.start($muzzle.global_position , rotation)
		cartridge -= 1

func _physics_process(delta):

func _on_interval_timeout():

func on_recharge():
	cartridge += 1
	print("Cartridge: " , cartridge)

This second script is from a different scene that is instanced in the scene from the first code. How can I connect them?

:bust_in_silhouette: Reply From: njamster
self.connect("recharge" , self , "on_recharge")

This is connecting the “recharge”-signal to the on_recharge-method. However, it will only happen when the signal is emitted from the same script. If you want to connect to a signal emitted by the parent-node you would do:

get_parent().connect("recharge" , self , "on_recharge")

In general:

<EmitterNode>.connect(<SignalName>, <ReceiverNode>, <CallbackName>)

where <EmitterNode> has to implement a signal with the name <SignalName> and <ReceiverNode> has to implement a function named <CallbackName>

My scene tree are like:

–area …

So, I tried to change the connect line to this:

$../../area".connect("recharge" , self , "on_recharge")

But I’m getting the error below:

Attempt to call function 'connect' in base 'null instance' on a null instance.

This is because shoot node is a packed scene?

malkav182 | 2020-04-04 01:28

The error means you’re using an incorrect path and instead of getting the correct node, you’re getting a null instance instead. Here are a few correct examples:

Connecting the game-node to the recharge-signal

$bottom/area.connect("recharge", self, "on_recharge")

Connecting the bottom-node to the recharge-signal

$area.connect("recharge", self, "on_recharge")

Connecting the shoot-node to the recharge-signal

$"../bottom/area".connect("recharge", self, "on_recharge")

njamster | 2020-04-04 09:56