How to solve attempt to call function ‘add_child ’ in base ‘null instance ’ on a null instance error

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By GM12

Hello Godoters,
I have been creating a text game by following the tutorials on youtube(here is the link https://www.youtube.com/watch?v=5gP1eOtR5Kg&t=1205s ) and I came to the point where I have to save the reusable scene by adding it to the GDScript here is the code:
extends Control

const InputResponse = preload(“res://InputResponse.tscn”)

onready var history_rows = $Background/MarginContainer/Rows/GameInfo/HistoryRows

func _on_Input_text_entered(new_text: String) → void:
var input_response = InputResponse.instance()
history_rows.add_child(input_response)

The problem is whenever I launch the game,the debugger pops up with the error message: attempt to call function ‘add_child ’ in base ‘null instance ’ on a null instance.

:bust_in_silhouette: Reply From: timothybrentwood

A node doesn’t exist at the node path Background/MarginContainer/Rows/GameInfo/HistoryRows at the time your control node that the script is attached to is _ready().

First try make sure that the NodePath listed above is valid.

If the NodePath above is valid and you are still getting the error, move the node that the script is attached to up in the scene tree so its _ready() function gets called later. Alternatively change your function, so you know that all nodes will be in the scenetree when you attempt to get them:

func _on_Input_text_entered(newtext: String) -> void:
    if not history_rows:
        history_rows = get_node("Background/MarginContainer/Rows/GameInfo/HistoryRows")
    var input_response = InputResponse.instance()
    history_rows.add_child(input_response)

More about how nodes are added to the scenetree:

:bust_in_silhouette: Reply From: jobieadobe

So when I “Copied Node Path” it copied everything but the root thing:
Background/MarginContainer/RowsVBox/ScrollContainer/VBoxContainer/VBoxContainer

My root is named Control so I changed my code to:

get_tree().get_root().get_node(“Control/Background/MarginContainer/RowsVBox/ScrollContainer/VBoxContainer/VBoxContainer”).add_child(button3)

And it worked! I hope this helps someone else.