I have a function that should make the sprite blink red every time the unit takes damage, but for some reason the massage “Invalid access to property or key ´modulate´ with value of type ´Color´ on base object of type ´null instance`”
func take_damage (damage_to_take):
health-= damage_to_take
if health <=0:
queue_free()
sprite.modulate = Color.RED
await get_tree().create_timer(0.1)
sprite.modulate = Color.WHITE
I have variable assigned to Sprite2D like so: var sprite : Sprite2D
I am pretty new in all this, so this is probably a pretty easy thing, but I just don’t figure the error out.
Are you calling this before node is ready?
When initializing scene, each node first processes its children and itself and only then are things that are needed at runtime (node references in this case) available.
If this is the case, you might need to await that ready signal:
if not is_node_ready():
await self.ready
Note that self.ready can be replaced with just ready
In this line, you are declaring the variable, but not assigning a value to it. Basically you’re telling the program “I will have a variable that is a Sprite2D”, but you are not giving this variable a value, so it defaults to null.
Did you assign an instantiated Sprite2D value to that value before calling sprite.modulate?
I call the function through the _process(delta) function through other functions, as far as my, very limited, understanding goes, that should be enough to call the function, isn’t that so?
I have basically copied the code form a tutorial I am following. No value had to be assigned to var sprite : Sprite2D and in the video everything was running fine.
Could it be that things have changed lately?
I don’t know if this worked differently in previous versions of Godot, but i am sure that you would get an error if you tried to access a property of an node with no value (null) in the current version.
Perhaps in the tutorial they assigned a value to the sprite variable through the inspector tab and not through code. if you change
var sprite : Sprite2D
to
@export var sprite: Sprite2D
that property will be displayed in the inspector (on the right side of the editor, by default) and you’d be able to select a sprite node from there to have that value assigned outside of code.
Again, i don’t know if the “@export” tag was needed for this in previous versions of Godot