Invalid set index 'texture' (on base: 'null instance')

Viewed 15

Invalid set index 'texture' (on base: 'null instance') with value of type 'StreamTexture'.

extends Panel

var ItemClass = preload("res://Item.tscn")
var item = "res://Blue Jeans.png"

func _ready():
    if randi() % 2 == 0:
        item = ItemClass.instance()
        add_child(item)

extends TextureRect

func _ready():
    if randi() % 2 == 0:
        $TextureRect.texture = load("res://Blue Jeans.png")
    else:
        $TextureRect.texture = load("res://Brown Boots.png")

I followed the exact tutorial on YT https://www.youtube.com/watch?v=FHYb63ppHmk but it seems to debug differently.

1 Answers

This line:

$TextureRect.texture = load("res://Blue Jeans.png")`

Loads a png as a StreamTexture using load, and tries to set it to the texture property of whatever $TextureRect is.

But the error says that there is no texture property on a null instance. Thus, the problem is that $TextureRect is a null instance.

So what does the expression $TextureRect do? It is equivalent to get_node("TextureRect"). In other words it is trying to get a child node called "TextureRect". And it is getting null…

Does the node on which the script is attached have a child node called "TextureRect"? You didn't share how the scene tree looks like, but I suspect it does not.

The script you shared says extends TextureRect, thus the script would be attached to a TextureRect. However, that is not what they do in the tutorial. In the tutorial the script is attached to a Node2D that has the TextureRect as child. You can see that at 4:10 on the tutorial video.

If you want to set the texture of the node on which the script is attached, set texture directly:

texture = load("res://Blue Jeans.png")`

Or if you rather be explicit, use self:

self.texture = load("res://Blue Jeans.png")`

On the other hand, if you are trying to follow the tutorial, then put the script on a node that has the TextureRect as a child (called "TextureRect"), and there $TextureRect would work.

Related