How can I fix error "Invalid get index 'position' _on base:'null instance').

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

Hello, while working on creating another enemy to spawn bullets I ran into an issue I have not faced yet. I did not change the script but now I get the error How can I fix error "Invalid get index ‘position’ _on base:(‘null instance’). What does it mean and how in my script can I fix it? Also why did this happen and what can I do to prevent it in the future I was on a role and I don’t want to have this happen again.

My code is as follows:

extends Node2D

var bullet_scene = load(“res://Bullet.tscn”)

onready var player = get_parent().get_parent().get_node(“PLayer”)
var type = “Enemy”

func _ready():
$Timer.set_wait_time(.5)
$Timer.start()

func _process(delta):
look_at(get_global_mouse_position())
position.y += 40 * delta

if(position.y > get_viewport_rect().size.y + 20):
	get_parent().remove_child(self)
	queue_free()

func spawn_bullets():

var b1 = bullet_scene.instance()
b1.position = self.position
b1.dir = Vector2(player.position.x - self.position.x, player.position.y - self.position.y).normalized()


get_parent().add_child(b1)

func timeout():
spawn_bullets()

Thanks!

It seems that the bullet is not getting instanced, maybe try onready var for bullet scene too. I am just a beginner, so, don’t take my word on it or anything. Also, try if bullet_scene == null : load(load(“res://Bullet.tscn”) in spwan bullets. Then do the instance stuff.

hamza_memon | 2020-08-22 04:27

:bust_in_silhouette: Reply From: AuthorSan

null instance basically means that the variable you are using is having a null value. It’s an error easy to debug in unity. For Godot, try adding this line into your code to see if your variable is actually null.

var bullet_scene = load("res://Bullet.tscn")
print(bullet_scene)
onready var player = getparent().getparent().get_node("PLayer")

if it shows null value in the output, try loading and instancing the scene on the same line.

var b1 = load("res://Bullet.tscn").instance()