#Inheritance: Define Sprite2D on Base Class, Create Texture on Derived Class

2 messages · Page 1 of 1 (latest)

candid token
#

Hi,
I am trying to create a base Fighter class script that can be re-used for all player and non-player scenes. The base Fighter class contains a Sprite2D variable and a custom _input(event) method to check if the Fighter was clicked.

I am able to successfully create and set the texture from inside Player.gd (the derived class) and render the sprite. The issue I am running into is that Fighter.gd loses reference to the 'sprite' variable and believes 'sprite' is null when the _input(event) method is invoked.

The error I am getting is: Cannot call method 'get_rect' on a null value.

Player.tscn is just a Node2D and there is no Fighter.tscn, just Fighter.gd.

In the future I plan on using AnimatedSprite2D or something else in place of Sprite2D for this. But I would like to understand what is causing the null value.

Fighter.gd

class_name Fighter extends Node2D

var sprite: Sprite2D

func _ready():
    sprite = Sprite2D.new()

func set_icon_texture(texture):
    sprite.texture = texture

func _input(event):
    if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
        if sprite.get_rect().has_point(to_local(event.position)):
            print("Clicked player")

Player.gd

class_name Player extends Fighter

var image = Image.load_from_file("res://icon.svg")
var texture = ImageTexture.create_from_image(image)

func _ready():
    super()
    set_icon_texture(texture)
    add_child(sprite)

func set_icon_texture(texture):
    super(texture)
mystic gust
#

It's probably because _input is being called by the engine before _ready. Try changing it to

func _input(event):
    if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
        #// sprite will evaluate to false if it is null
        if sprite and sprite.get_rect().has_point(to_local(event.position)):
            print("Clicked player")