AnimatedSprite causing fatal error upon game launch

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

I am relatively new to Godot and programming, but I have tried just about everything and nothing has worked. Here is my problem:

I want to make a simple walk cycle animation. I am using modified code from the Godot documentation for 2D sprite animation1. My full AnimatedSprite.gd file looks like this:

extends KinematicBody2D

func _process(delta):
if Input.is_action_pressed("right"):
	$AnimatedSprite.play("walk_right")
else:
	$AnimatedSprite.play("default_right")

if Input.is_action_pressed("left"):
	$AnimatedSprite.play("walk_left")
else:
	$AnimatedSprite.play("default_left")

My AnimatedSprite is a child of a KinematicBody2D, and the AnimatedSprite has 4 animations in it: one left-facing walk cycle, one right-facing walk cycle, one neutral idle animation facing right, and one neutral idle animation facing left. I get no errors in my AnimatedSprite.gd code until I run the game, upon which I receive this fatal error that crashes the game as soon as the Godot logo appears: Script inherits from native type 'KinematicBody2D', so it can't be instanced in object of type: 'AnimatedSprite'. This error supposedly comes from the first line of my code, extends KinematicBody2D. So I try to fix the error by changing extends KinematicBody2D to extends AnimatedSprite. Upon doing that, I get another fatal error that crashes the game at the Godot logo: Attempt to call function 'play' in base 'null instance' on a null instance. Looking at this further in the debug console, this error is further refined as get_node: Node not found: AnimatedSprite. This isn’t right, because I have an AnimatedSprite node that this script is attached to.
If anyone can help with this, I would really appreciate it. I have been working on debugging this for about 2 days now and nothing has worked. If anyone would like to take a look at the project file for further inspection of my code, let me know. Thank you for your help.

:bust_in_silhouette: Reply From: njamster

This error supposedly comes from the first line of my code

Correct. And you fixed it! :slight_smile:

This isn’t right, because I have an AnimatedSprite node that this script is attached to.

If your script is attached to the AnimatedSprite, it should look like this:

extends AnimatedSprite

func _process(delta):
    if Input.is_action_pressed("right"):
        play("walk_right")
    else:
        play("default_right")

    if Input.is_action_pressed("left"):
        play("walk_left")
    else:
        play("default_left")

It is calling the play-method on itself and not a child-node called “AnimatedSprite”.

Thank you so much! This worked perfectly.

mextie-dev | 2020-04-27 17:46