Can't load player data to nodes in other scenes

Thanks. Good catch. I admit I did not look at the screenshot. The solution in this case is a very easy one: Player Detection.

There are two methods I would recommend. One is only for bullet hell games. The other is for everything else.

Bullet Hell

In this case, you spawn the enemies, they rush the player and die. So just do this:

  • Add the player to a group called “Player”.
  • Add code to the enemy in _ready()
var player: CharacterBody2D

func _ready() -> void:
	player = get_tree().get_first_node_in_group(&"Player")

Then use it.

All Other Games

If you have a game where the Enemy shouldn’t see the Player if they’re too far away, or through a wall, you need a more complex solution.

  1. Add an Area2D to the Enemy.
  2. Rename it DetectionArea. (The name doesn’t matter, we’re just using it for our code below.)
  3. In the Inspector change the Collision Mask for the DetectionArea so it only detects Layer 2. (You can right-click on it to change it to rename it to Player. Choose a different layer if there’s already something on this one.)
  4. Add the Player to that Physics Layer in the Inspector.
  5. Then add a CollisionShape2D to DetectionArea.
  6. Add a CircleShape2D to the Shape in the Inspector. (I also changed the debug color to a yellow.)
  7. Add code to your Enemy script:
var player: CharacterBody2D

@onready var detection_area: Area2D = $DetectionArea


func _ready() -> void:
	detection_area.body_entered.connect(_on_player_detected)
	detection_area.body_exited.connect(_on_player_lost)


func _on_player_detected(body: Node2D) -> void:
	player = body


func _on_player_lost(body: Node2D) -> void:
	player = null
4 Likes