Access variable after pre-loading/instatiating a script from another script

Godot Version

4.2

Question

I have a script, call A, attached to my scene A.
This script A pre-loads another script, B, and tries to execute a function from the loaded script.
Script B preloads a scene X and tries to access in the function called, but the scene is null, thus throwing an error. What can I do to make the scene not null? I don’t want to autoload script B.

Here is a simple example of how they are being executed:

# script A

@onready var scriptB = preload("res://scriptB.gd").new()

func _ready():
    scriptB.load(get_node("."))
# script B

@onready var sceneX = preload("res://sceneX.tscn")

func load(node):
    var x = sceneX.instantiate() # throws an error here, because sceneX is null.
    node.add_child(x)

func _ready():
    print("this line never gets called") # I think I know this one, since the script is not attached to a running scene?

Thanks in advance.

what does script B extends? if it has no Extends Node, then you cant use the _ready()

It has extends Node. Both scripts have that. I omitted for simplicity.

Ok, I believe I need to use _init instead of _ready and that should do the trick. Thanks.

is basically for object when it’s newly created or .new()
this works because Node is also inherited Object, so Node can use Object’s method _init()

only works if you are using a Node and after add_child the node to the scene

alternatively, if you will never add_child the script, you can just make it extends RefCounted ,not all things has to be a extends Node