Why the node is null

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

I don’t understand why I getting this error, the node is there but the editor keeps telling the node instance is null. It would be helpful if someone could point out where the problems is, thank you.

ERROR: Invalid set index ‘texture’ (on base: ‘null instance’) with
value of type ‘StreamTexture’

Door (Area2D)

  • Sprite


extends Area2D

onready var sprite = $Sprite
export var type = 0 setget set_texture

func set_texture(newSprite):
	type = newSprite
	if type == 1:
		sprite.texture = load("res://Image/Door01.png") 
	if type == 2:
		sprite.texture = load("res://Image/Door02.png") 
:bust_in_silhouette: Reply From: Wakatta

It depends on where you’re calling set_texture() like for instance if you had that function in _enter_tree() or _init() before the node even enters the sceneTree can cause that.

Also onready var sprite = $Sprite states that Sprite is a direct child of Door

Thanks for the comment, as you mention it is likely caused by the node has been called before _ready. I have added a line of if is_instance_valid(sprite):in the set_texture function, and it works.

As for the node relation, Sprite is a direct child of Door. Is it better to use Sprite as parent node and Area2D as a child node? Thank you.

Idleman | 2021-01-20 22:08