How to assign an exported variable when instantiating a scene in a script

Godot Version

4.3

Question

I’m an absolute beginner and I’m using Godot 4.3, GDScript. Trying to add a spawning system for enemies in a 2D game, but currently i have a variable named ‘Player’ exported, in which I have to assign the player node (named ‘player’) so that the path finding knows what to track. Using a script to spawn these enemies only shows errors because when they instantiate a new enemy to spawn, the enemy has no player node assigned. How do i make the script auto assign it to the player. The player is a child of the main level node. The enemy is its own scene with a pathfinding script. Please tell me if i need to provide more information. I’ve asked previously on reddit, but i didn’t understand the answers so if you could tell me where to put lines of code etc that would be great.

main level script with the spawning: SCRIPT ATTACHED TO MAIN LEVEL NODE - Pastebin.com

enemy script with the pathfinding: SCRIPT ATTACHED TO ENEMY NODE - Pastebin.com

that’s not how you are supposed to use exports.

there are much better ways to tell an enemy where the player is.

1 - with groups, put the player node into a group, call it something like “player”. then in the enemy assign a var in ready.

var player

func _ready() -> void:
	var player_nodes : Array[Node] = get_tree().get_nodes_in_group("player")
	if not player_nodes.is_empty():#there are nodes in player group
		player = player_nodes[0]#get first element

2 - other ways could be with an autoload or using an Area as line of sight for the enemy, which is useful in stealth or stealth adjacent games.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.