Enemy Issues

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

Sorry to bother you, but when you defeat an enemy in my game, it’s meant to explode, but for some reason, an error occurred, saying: Attempt to call function “play” in base “null instance” on a null instance

extends Area2D

signal score_add
signal enemy_died(damage, location)
signal spawn_enemyLaser(Laser, location)

var Laser = preload("res://Scenes/GSILaser.tscn")



export var speed = 35

export var hp = 3
onready var muzzle = $Muzzle
export var damage = 2

func _ready():
	pass

func _physics_process(delta):
	global_position.y += speed * delta
	



func _on_Area2D_area_entered(area):
	if area is Player:
		area.take_damage(damage)
	elif area.is_in_group("player_laser"):
		area.take_damage(damage)
		$AnimatedSprite.play("Animation2")

	if area.is_in_group("bottom"):
		pass


func take_damage(damage: int):
	hp -= damage
	$HitSound.play()
	if hp <= 1:
		$AnimatedSprite.play("Animation3")
		$HitSound.play()
	if hp <= 0:
		$AnimatedSprite.queue_free()
		$AnimatedSprite2.play("Explode")
		get_node("CollisionPolygon2D").disabled = true
		emit_signal("score_add")
	


func _on_RSI_spawn_laser(Laser, location):
	var laser = Laser.instance()
	add_child(laser)
	laser.global_position = location



func _on_Timer_timeout():
	emit_signal("spawn_enemyLaser", Laser, muzzle.global_position)


func _on_Area2D4_area_entered(area):
	if area.is_in_group("enemy"):
		pass



func _on_enemy_died(damage, location):
	$HitSound.play()


func _on_VisibilityNotifier2D_screen_entered():
	get_node("CollisionPolygon2D").disabled = false


func _on_VisibilityNotifier2D_screen_exited():
	get_node("CollisionPolygon2D").disabled = true


func _on_AnimatedSprite2_animation_finished(Explode):
	queue_free()
:bust_in_silhouette: Reply From: Midonk

The error says it well: something where you are attempting to call a play function (either $HitSound, $AnimatedSprite or $AnimatedSprite2) is null so it don’t find the reference in your tree. You may set a breakpoint on the potential problematic ligns (F9) to check the value of each variable at runtime

:bust_in_silhouette: Reply From: Gluon

Any time you get the error “Attempt to call function XXX in base ‘null instance’ on a null instance” it means you have tried to get_node a node that doesn’t exist.

I notice at one point you clear Animated Sprite 1 and immediately make a call too $AnimatedSprite2.play(“Explode”). Is AnimatedSprite2 already in the scene or did you intend to create an instance of animated sprite 2 first?

Beyond that all I can suggest is comment out each of the instances of play one at a time until you no longer get the error message. That will at least tell you which line is causing the issue.