Invalid access to property or key 'global_position' on a base object of type 'Nil'. why

Godot Version

godot 4.7.2

Question

Ive finally fixed my previous issue but now somethings wrong with the global position


   extends CharacterBody3D

@export var WalkSpeed: float = 1.5
@export var RunSpeed: float = 4.0
@export var AttackReach: float = 1.5

@onready var navigation_agent: NavigationAgent3D = $NavigationAgent3D

var player: CharacterBody3D = null

func _ready() -> void:
	var players = get_tree().get_nodes_in_group("player")
	if players.size() > 0:
		var player = players[0]
		print("found player:", player.name)

func _process(delta: float) -> void:
	navigation_agent.set_target_position(player.global_position)
	
	if global_position.distance_to(player.global_position) < AttackReach:
		var attack: Attack = Attack.new(1.0, self)
		player.health_component.damage(attack)



func _physics_process(_delta: float) -> void:
	process_move()


func process_move() -> void:
	#if navigation_agent.is_navigation_finished():
		#return
	
	#var next_position: Vector3 = navigation_agent.get_next_path_position()
	#velocity = global_position.direction_to(next_position) * WalkSpeed
	
	move_and_slide()


func on_death() -> void:
	queue_free()

player is null. You never initialize it to an actual node reference.

like what normalized said, you never initailized the player. Do you have a seprate player scene?

If you havent yet, you do need to make a new player scene. Then, from your files area, youre gonna link the player scene into the scene youre working in, and then youre gonna drag it into this code, which will be in the script of your main node:

var player = #drag it in here

Tell me if you need more help :smiley:

I’m not sure what you mean by main code, like replace the null code? it uses to work before I tried making the enemy wander

You are initializing a new local variable in your _ready() method, instead of the class member.

var player = players[0]

Try instead

self.player = players[0]

yeah, delete the var player: Charecter3D = null and replace it with that