I have an error and I don't know how to fix it.

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

Hi
I can’t seem to find out what I’m doing wrong here. I have it so the player can create bombs but currently whenever you try to do so it crashes. The error that shows up is Invalid set index ‘position’ (on base:‘PackedScene’) value of type ‘Vector2’.
Here is the relevant code.

const BOMB = preload("res://source/actors/Bomb.tscn")

func _physics_process(delta):
if Input.is_action_pressed("Move_right"):
	velocity.x = SPEED
	$anim.play("walking right")
	$anim.flip_h = false
elif Input.is_action_pressed("Move_left"):
	velocity.x = -SPEED
	$anim.play("walking right")
	$anim.flip_h = true
else:
	velocity.x = 0
	if on_ground == true:
		$anim.play("1")

if Input.is_action_just_pressed("place_bomb"):
	if on_ground == true:
		velocity.y = JUMP_POWER
		on_ground = false

	if Input.is_action_just_pressed("place_bomb"):
		var t = Timer.new()
		t.set_wait_time(0.15)
		t.set_one_shot(true)
		add_child(t)
		t.start()
		yield(t, "timeout")
		var bomb = BOMB.instance()
		get_parent().add_child(bomb)
	BOMB.position = $Position2D.global_position
	var BOMB = BOMB.instance()
	World.add_child(BOMB)

(I have code in between but it is irrelevant variables that aren’t the problem.) The point at which it crashes is at ‘BOMB.position = $Position2D.global_position’. I think it has to do with the way I’m preloading the bomb. It is a node2D. Sorry for the long mess.
Thanks for the help!
-“The new guy”

:bust_in_silhouette: Reply From: kidscancode

In your code BOMB is a scene you’ve loaded from a file. This means it is a PackedScene object. A PackedScene contains all the information about what nodes, data, etc. make up your object.

We use the PackedScene’s instance() function to actually create all of those nodes. You are doing this when you do the following:

    var bomb = BOMB.instance()
    get_parent().add_child(bomb)

This is fine - you’ve created an instance of BOMB and called it bomb and added it to the tree. However, on the next line, you try do to these things:

BOMB.position = $Position2D.global_position
var BOMB = BOMB.instance()
World.add_child(BOMB)

This is problem because

  1. BOMB doesn’t have a position - it’s not a node, it’s the PackedScene.
  2. var BOMB = BOMB.instance() - you’re deleting your PackedScene by replacing it with an instance.

You’re already doing the right thing when you create the instance called bomb, so just set bomb.position to what you want.

You also have some strange things going on with your indentation under the is_action_just_pressed("place bomb"). Why do you have it there twice?

Thank you so much!

Large Sleeves | 2020-08-28 23:13