Invalid set index 'position' (on base: 'null instance') with value of type 'Vector2'.

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

Hello
I have a problem
when creating an item in the conditions, I get errors
but when code snippets are removed, everything works without errors
here is the error in the debuggers:

  1. loading: unable to load dependency: res://prefab/item.res.
  2. __load: Failed to load resource: res://scene/world.scene. Verify that the resources have been imported by opening the project in the editor at least once.
  3. set_path: Another resource is loaded from the path ‘res://scene/world.scn’ (possibly cycling the resource).
  4. item.gd:47 @ _process(): Condition “nc == 0” is true. Return: nullptr
  5. item.gd:48 @ _process(): parameter “p_child” is null.
  6. Invalid specified index “position” (based on: “null instance”) with a value of type “Vector2”.
    code that causes errors:
extends Area2D

# [ НАСТРОЙКА ]

# name
@export var key = ""
@export_multiline var decs = ""

@onready var player = get_parent().get_node("player/inventory") # ссылка на игрока
@onready var world = get_parent().get_parent().get_node("world") # ссылка на мир

# переменная
var enter = false # соприкосновение с игроком
var pickup = false # в инвентаре 
var craft_id = 0 # крафт ?

var kd = 1.5 # кд начало
var kd_ = 0 # кд использовние

func _ready():
	$name.text = key
	$name.hide()
	$anim.play("ilde")
	
func _process(_delta):
	# кд система
	kd_ -= 0.01
	
	# если мы вошли в колизию
	if enter == true:
		$name.show() # показ текста
		if Input.is_action_just_pressed("use") and player.get_child_count() < 1: # если мы нажали "E"
			pickup = true # включение для того что-бы добавить
			add() # подбор
			
	if Input.is_action_just_pressed("drop") and pickup == true:
		drop()
			
	# использование 
	if pickup == true:
		use() # использование
		
	# крафт
	if enter == true and player.get_child_count() == 0:
		if craft_id == 1:
			if Input.is_action_just_pressed("craft"):
				var spawn = preload("res://scene/world.scn").instantiate()
				get_parent().add_child(spawn)
				spawn.position = player.global_position

			$name.text = "Q"
			$body.shape.radius = 8
		else:
			$name.text = key
			$body.shape.radius = 5
		

# использование
func use():
	# default
	$name.hide() # скрытие надписи
	look_at(get_global_mouse_position()) # поворачиваеи на курсор
	# система поворота
	if get_global_mouse_position().x < global_position.x:
		self.scale.y = -1
	else:
		self.scale.y = 1
		
	if Input.is_action_pressed("LMB") and kd_ <= 0:
		$anim.play("use")
		kd_ = kd
	# custom
	

# подбор
func add():
	get_parent().remove_child(self) # удаления из прена нас
	player.add_child(self) # добовляем себя дочерний узел игроку
	self.position = Vector2.ZERO # устанавливаем позицию
	$art.offset.x = 2 # отдаляем от тела
	$name.hide() # скрытие надписи

# дроп 
func drop():
	player.remove_child(self) # удаляем себя из игрока
	world.add_child(self) # миру добовляем себя
	rotation_degrees = 0 # поворот = 0
	self.position = player.global_position # выбрасываем под игрока
	self.scale.y = 1 # возращяем поворот
	$art.offset.x = 0 # стандарт
	pickup = false # выключаем
	$name.hide() # скрытие надписи

func _on_area_entered(area):
	if area.is_in_group("test"):
		craft_id = 1

func _on_area_exited(area):
	if area.is_in_group("test"):
		craft_id = 0


func _on_body_entered(body):
	if body.is_in_group("player"):
		enter = true

func _on_body_exited(body):
	if body.is_in_group("player"):
		enter = false
		$name.hide() # скрытие надписи

I have attached a video where I show the errors and how they are supposed to be:

thank you in advance

As humans, we have a responsibility to protect and care for animals. It’s not just about compassion, but also about ensuring that the environment we share with them is safe and healthy. Please checkout: Animal Welfare

kitticpet | 2023-03-11 07:11

:bust_in_silhouette: Reply From: aidave

You shouldn’t be doing this:

var spawn = preload("res://scene/world.scn").instantiate()

That should just be load().

Or use preload() for const in the var declarations:

const spawn_tscn = preload("res://scene/world.scn")
var spawn = spawn_tscn.instantiate()

Also you must open your “world.scn” in the editor and check that for load errors. Not sure why it has “.scn” extension?

Also is “world.scn” the craft item? Because it has an odd name for a craft item.

aidave | 2023-03-10 13:14

hi,
I tried to do as they said above,
but the error is exactly the same,
here is the code that I tried:

if enter == true and player.get_child_count() == 0:
		if craft_id == 1:
			if Input.is_action_just_pressed("craft"):
				const  spawn_tscn = preload("res://prefab/tree.tscn")
				var spawn = spawn_tscn.instantiate()
				world.add_child(spawn)
				spawn.position = player.global_position

error:

1. E 0:00:11:0781   item.gd:49 @ _process(): Parameter "p_child" is null.
  <Исходный код C++>scene/main/node.cpp:1130 @ add_child()
  <Трассировка стека>item.gd:49 @ _process()

2. E 0:00:11:0781   item.gd:48 @ _process(): Condition "nc == 0" is true. Returning: nullptr
  <Исходный код C++>scene/resources/packed_scene.cpp:88 @ instantiate()
  <Трассировка стека>item.gd:48 @ _process()

3. E 0:00:01:0772   set_path: Another resource is loaded from path 'res://prefab/tree.tscn' (possible cyclic resource inclusion).
  <Ошибка C++>   Method/function failed.
  <Исходный код C++>core/io/resource.cpp:75 @ set_path()

4. E 0:00:01:0763   _load: Failed loading resource: res://prefab/tree.tscn. Make sure resources have been imported by opening the project in the editor at least once.
  <Ошибка C++>   Condition "found" is true. Returning: Ref<Resource>()
  <Исходный код C++>core/io/resource_loader.cpp:222 @ _load()

5. E 0:00:01:0762   load: res://prefab/tree.tscn:3 - Parse Error: [ext_resource] referenced nonexistent resource at: res://code/tree.gd
  <Исходный код C++>scene/resources/resource_format_text.cpp:490 @ load()

BOX_Milk | 2023-03-10 16:32

I was just looking at which nodes it can spawning

BOX_Milk | 2023-03-10 16:34

You can’t have const inside a function.

It’s likely you are loading scenes that are broken if it doesn’t error before const

I recommend taking a step back and reading the GDScript definition docs and some tutorials, because there is too much wrong with your code.

GDScript reference — Godot Engine (stable) documentation in English

aidave | 2023-03-10 18:33

:bust_in_silhouette: Reply From: BOX_Milk

I found a way out
it’s all about the team

var spawn = preload("res://prefab/tree.tscn")

should have been replaced with

var spawn = load("res://prefab/tree.tscn")

Someone else took the time to help you, then you rewarded yourself the best answer. Nice

aidave | 2023-03-11 17:11