0 votes

Hello!

I have a script that outputs an error:
Invalid set index 'global position' (on base: null Instance) with value of type 'Vector2'.

But I don't know what possibly could be wrong.

This is my code:

extends Node2D


onready var orangeball = $orangeball0
var doneCreatingBalls = false

func _ready():
    for i in 11:
        orangeball.duplicate()
        orangeball.name = "orangeball" + (i + 1) as String
    doneCreatingBalls = true

func _physics_process(_delta):
    if doneCreatingBalls == true:
        for i in 12:
            get_node("orangeball" + i as String).global_position = get_node(i as String).global_position

And this is my node tree (If that is helpful):
My node tree

Godot version 3.3.4
in Engine by (26 points)

1 Answer

+3 votes
Best answer

"orangeball" + (i + 1) as String seems wrong. Try str("orangeball" + (i + 1)).

How you're accomplishing what you're trying to do doesn't make use of the tools built into the engine very well. I would recommend attaching a script to your number nodes (0-12) and making them spawn the balls. Attaching a script that contains this:

func _physics_process(_delta):
    var new_ball = get_node("orangeball").duplicate()
    get_parent().add_child(new_ball)
    new_ball.global_position = self.global_position

To any of your numbered nodes will accomplish what you were trying to accomplish in a much more decoupled manner. Attach that script to 0, then simply duplicate that node in the editor and it will work.

It's generally bad practice to refer to nodes by their name. It's preferable to use groups or class names instead. add_node_to_group() and get_tree().get_nodes_in_group() is generally how you want to refer to nodes that you instance at runtime.
https://docs.godotengine.org/en/latest/tutorials/scripting/groups.html

Adding class_name MyNode to a node's script allows you to make comparisions like if some_node is MyNode:. This is useful for collisions and other scenarios where you want to know if a unknown node is a specific type of node that you created at runtime.

by (3,768 points)
selected by

Ah, yes, thanks. I am fairly new to the Godot engine, so I apologize for any inconvenience.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.