I get "Invalid access to property or key 'global_position' on a base object of type 'null instance'. " error

Godot Version

4.3

Question

I’m making a skeleton enemy according to the tutorial “Projectile and RayCast2D in Godot 4” by “16BitDev” that will track the player’s location with RayCast.
Code:


@onready var ray_cast: RayCast2D = $RayCast
var has_a_bomb : bool = true
var is_dead : bool = false
enum skeleton_type {WITH_BOMB, WITH_KNIFE}
@export var skeleton : skeleton_type

var player

func _ready() -> void:
	player = get_tree().get_root().get_node("Player")
	
func _physics_process(delta: float) -> void:
	_aim()
	_check_player_collision()

func _aim():
	ray_cast.target_position = to_local(player.global_position) <-- here's problem
	
func _check_player_collision():
	pass

Hierarchy :
image

Please help!

It means that the player is null, can you try this?

player = get_tree().current_scene.get_node("Player")
1 Like

it doesn’t work, just in case I changed the line in the _ready() function to what you wrote

1 Like

Can you recheck that the player is actually exists in the scene in game? While the game is running (or shows error), at the top of the scene tree you will find a “remote” tab where you can observe every nodes in-game.

1 Like

Yes, the player exists in the scene. Here’s a screenshot:

Can you try this:

player = get_tree().get_root().get_node("TestWorl").get_node("Player")

Doesn’t work

1 Like

Not sure why its not working, last try from me is to first define a Global autoload and define player variable. In the player script, do Global.player = self, then do like this:

func _aim():
	if Global.player: ray_cast.target_position = to_local(Global.player.global_position)

It works, but how can I make it so that not a separate scene is indicated, but the current one?(current scene is doesnt work😥)

Why not use groups instead?

In player script:

func _ready() -> void:
 	add_to_group("player")

Where you need to get the player reference:
var player = get_tree().get_first_node_in_group("player")

2 Likes

Cannot call method ‘get_first_node_in_group’ on a null value.
Skeleton Code:

extends CharacterBody2D

@onready var ray_cast: RayCast2D = $RayCast
var has_a_bomb : bool = true
var is_dead : bool = false
var player = get_tree().get_first_node_in_group("Player")
enum skeleton_type {WITH_BOMB, WITH_KNIFE}
@export var skeleton : skeleton_type

	
func _physics_process(delta: float) -> void:
	_aim()
	_check_player_collision()

func _aim():
	ray_cast.target_position = to_local(player.global_position)
	
func _check_player_collision():
	pass

The group with the player is global, I set it up and the local one does not work (

Because you’re trying to get the tree before the scene is started, use that on _ready function

And if player is already in scene while the game is running, you can just place @onready before it like @onready var player…

It will not work if you add the player into the scene by codes.

It worked! Thanks everyone!

1 Like