It is giving me an error for get_root. HELP!

This error always shows up whenever I run my game on godot: Cannot call method ‘get_root’ on a null value.

Script: `extends CharacterBody2D

@onready var progress_bar: ProgressBar = $ProgressBar
var player = get_tree().get_root().get_node(“/root/Game/Player”)
var speed: float = 0.01

Called when the node enters the scene tree for the first time.

func _ready() → void:
progress_bar.value = Global.enemyHits

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _process(delta: float) → void:
progress_bar.value = Global.enemyHits
look_at(player.global_position)
self.position = lerp(self.position,player.global_position,speed)
`

It was working before for a little then it just stopped.

Github: GitHub - kaihan-man/TopDownShooter: This is a topdownshooter

Add the @onready to your player variable declaration.

@onready var player = get_tree().get_root().get_node(“/root/Game/Player”)

The error you got was because you tried to call get_tree() before the node entered the scene tree, so it returned null. Then, you called your get_root() on a null value - hence the error message. The @onready ensures this piece of code is ran only after the node entered the scene tree and is ready.

1 Like