Yes, you can link to another object. Let’s assume you have this scene tree:
Area2D (your zone)
├─ CollisionShape2D
└─ SpawnerInstance
Assuming your script is attached to the Area2D, you can connect a function to the signal like this:
@onready var spawner = $SpawnerInstance
func _ready():
body_entered.connect(spawner._spawner_ready)
Or use the UI in the editor. You can select the Area2D and head to the “Node” dock, then select the signal and connect it to your spawner node function.
Ok I think there is a few things confused here. So let’s start with a few definitions:
- Script:
This is the source code file you have. In itself, it does nothing. It can be instanced to create objects.
- Instance/Object:
This is an object in the engine, possibly with a script attached. This is what you can call functions on.
When you run your game, all the nodes in your scene are instances. Some may have a script attached. There can even be multiple instances with the same script (for example, you can have one enemy.gd
script and instance it multiple times to have multiple enemies.
- Scene File:
This is a tscn
file to save what a scene contains. Think of it as a kind of “blueprint” for creating a scene. In itself it does nothing. It must be instantiated (for example, by loading it as the main scene. Or by including an instance of it in another scene).
The TL;DR of this is: You need a reference to an object if you want to call a function on it.
Now let’s look at your code. The following line loads a Scene File:
@export var SPAWNER = preload(“res://scripts/spawner.tscn”)
That is just a blueprint of how to create the spawner scene. It does not know about it’s instances (and it can’t. Like imagine this was the blueprint for an enemy scene: There could be many different instances of that scene file, so there is no way to know which enemy instance you want to use).
So instead of this, you need to get a reference to the actual Instance of the spawner scene. The usual way is to use a node path. Now, I don’t know your scene layout. But let’s say you have a node tree like this:
Area2D (your zone)
├─ CollisionShape2D
└─ SpawnerInstance
Then when your script is attached to the Area2D
, then the node path would be $SpawnerInstance
as it is the direct child.
So your code would need to look like this (note the onready keyword, you can only access stuff from the scene tree once the tree is ready:
@onready var spawner = $SpawnerInstance
func _on_area_2d_body_entered(body: Node2D):
spawner._spawner_ready()