0
votes

First of all, I'm new to programming in general so I'm kind of assuming there's a simple answer to this question, I just couldn't seem to find it anywhere. I'm making a simple platformer game with enemies that move toward the player. I used this code in the enemy's script underneath the physics process to get the player position:

player_position = get_parent().get_node("Player").get_position

However, upon the player being queue_freed when health reaches 0, the game crashes immediately and I get a null error due to there being no Player node. How can I work around this?

3

3 Answers

1
votes

You could just set $Player.visibility to false instead of freeing, or you could check if the player exists first using get_parent().has_node("Player")

1
votes

When you destroy the player, the physics process function is still trying to get the player node, even though it doesn't exist. So, as Lucas said, you could replace:

player_position = get_parent().get_node("Player").get_position

with something like...

if get_parent().has_node("Player"):
    player_position = get_parent().get_node("Player").get_position

(Before setting player_position, it will check if the player node even exists)

1
votes

I think you could use weakref (documentation here).

If you declare a weak reference:

var player_ref: WeakRef = null

and store that reference:

func store_player_node():
    var player_ref = weakref(get_parent().get_node("Player"))

Then you can access that reference later:

if player_ref.get_ref():
    player_position = player_ref.get_ref().get_position

Weakref has advantage over using get_parent().get_node("Player"). Let's imagine the following scenario:

  1. Player dies and its node is removed from the parent node's children.
  2. New node is created with name Player and added to the scene tree at the same place as the dead Player.
  3. get_parent().get_node("Player") will return a node and the code will not crash. However, it will be a new Player node, not the old one, and I think this is usually undesired.

I hope this helps!