Calling a Method / Using signals on a PackedScene

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

Hello there,

I am working on a enemy that I want facing the player AT ALL TIMES. The thing is, The enemy is a scene on its own that I instance only when a certain event occurs ( Pressing a button for example ). I want to send the player’s coords every single frame to the enemy to consume, but I can’t seem to make it happen. What I have tried:
1 - Calling a method from the players script each frame, However, You can’t call methods on packedScenes
2 - Using signals, Having the same issue to reference to the packedScene enemy.

Is there anyway to do it?

The enemy may be a PackedScene object, but have you tried instancing that object, and calling the methods on the instance?

Ertain | 2022-04-28 18:34

I did try that. I want the enemy to know the player’s position at every frame, So I am handling that at the _process function, The thing is, I am not instancing my enemy scene in there. I do it in a separate function. Is there a way to?

JCNegar | 2022-04-28 19:28

So the enemy scene has been instanced? Is the instanced scene a different object from PackedScene? Does the code for instancing the enemy scene look like this?

var enemy_scene = preload("res://path/to/enemy.tscn")
# Assign the enemy instance to this variable later.
var enemy1

# When the enemy scene needs to be instanced.
func _put_in_enemy(location: Vector2):
    # Is the variable `enemy1` of the type `KinematicBody2D`?
    var enemy1: KinematicBody2D = enemy_scene.instance()
    enemy1.position = location

# Move the enemy around here.
func _physics_process(delta):
    ...
    enemy1.position = location_near_player
    ...
    

Ertain | 2022-04-28 20:27

Hello there, Yes. I used almost exactly the same code as yours. I solved the problem thanks to your code, What I was basically doing is declaring the enemy1 variable inside a custom function making the rest of the script unable to access it. Declaring the variable at thr start of the script ( Just as you did ) did the trick for me. Thanks a ton

JCNegar | 2022-04-29 12:54