I'm trying to make a character shoot. My shoot code is almost the exact same as the code used in the 2D platformer demo (save for some names.). Here's the player code:

`extends KinematicBody2D

const UP = Vector2(0, -2) const GRAVITY = 15 const MAX_SPEED = 175 const JUMP_HEIGHT = -290 const ACCELERATION = 20 const BULLET_VELOCITY = 1000 signal dead var jump_count = 0 var motion = Vector2() var anim = ""

func _physics_process(delta): motion.y +=GRAVITY motion.x = min(motion.x, MAX_SPEED) if Input.is_action_pressed("ui_right"): motion.x = min(motion.x+ACCELERATION, MAX_SPEED) $Sprite.scale.x = 1 elif Input.is_action_pressed("ui_left"): motion.x = max(motion.x-ACCELERATION, -MAX_SPEED) $Sprite.scale.x = -1 else: motion.x = 0

if is_on_floor():
	jump_count = 0
	if Input.is_action_just_pressed("ui_up"):
		motion.y = JUMP_HEIGHT
		jump_count = 1
elif jump_count < 2 and Input.is_action_just_pressed("ui_up"):
	motion.y = JUMP_HEIGHT + 30
	jump_count = 2
	$Jump_Particle.emitting = true
motion = move_and_slide(motion, UP)

if Input.is_action_just_pressed("ui_accept"):
	var bullet = preload("res://Bullet.tscn")
	bullet.position = $Sprite/gun_shoot.global_position
	bullet.linear_velocity = Vector2(Sprite.scale.x * BULLET_VELOCITY, 0)
	bullet.add_collision_exception_with(self)
	get_parent().add_child(bullet)`

However, I get the error shown in the question title. I'm not sure how to combat this.

In case you're wondering, here's the player tree:

Help appreciated. I'm still new to Godot, so please try to keep it simple.

You've loaded the bullet, but you have not instanced it yet. You have to instance a loaded, or preloaded, scene so it's spawned/copied/duplicated into a variable. Then you can add it using add_child and it should work.

Changing the code under if Input.is_action_just_pressed("ui_accept"): to the following should fix it:

if Input.is_action_just_pressed("ui_accept"): var bullet = preload("res://Bullet.tscn").instance() bullet.position = $Sprite/gun_shoot.global_position bullet.linear_velocity = Vector2(Sprite.scale.x * BULLET_VELOCITY, 0) bullet.add_collision_exception_with(self) get_parent().add_child(bullet)


Personally, I would suggest making one small change though, to save on performance. Instead of loading the scene every time you want to fire a bullet, why not instead load the scene once and then use that instead.

You can do this by adding the following to your class variables (Variables outside of any functions): const BULLET_SCENE = preload("res://Bullet.tscn")

Then you just need to change var bullet = preload("res://Bullet.tscn").instance() to var bullet = BULLET_SCENE.instance(). Then it will only load the bullet scene once.

5 years later