Cannot move duplicate object

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

I want new random levels to generate and move where I want.
I tried this code but a error said Invalid set index ‘translation’ (on base ‘NIL’) with value type of 'Vector3

extends Spatial

var rand = RandomNumberGenerator.new()

onready var Levi = $i/RootNode/Plane002
onready var Levii = $ii/RootNode
onready var Leviii = $iii/RootNode/Plane
onready var Leviv = $iv/RootNode/Plane003

var last_pos = 0
var new_lev = Levi
func _ready():
    pass

func _process(delta):
    if rand.randi_range(1,4) == 1:
	    new_lev = Levi.duplicate()
    elif rand.randi_range(1,4) == 2:
	    new_lev = Levii.duplicate()
    elif rand.randi_range(1,4) == 3:
	    new_lev = Leviii.duplicate()
    elif rand.randi_range(1,4) == 4:
	    new_lev = Leviv.duplicate()
	
    new_lev.translation = Vector3(last_pos + 0.5,0,0)
    last_pos += 0.5
:bust_in_silhouette: Reply From: jgodfrey

There are likely a few problems here:

First, this is probably not working as you intend:

var new_lev = Levi

At the time that code executes, the Levi var probably hasn’t been set yet. So, initially, the new_lev var is null.

Now, when you get into your _process() function, you have a logic issue.

You don’t want to call rand.randi_range() for each block there. You need to call it only once and then analyze the results. With the current code, you’re very likely falling through all of the checks without ever matching any of the blocks. When that happens, new_lev never gets reset to a valid value (and, so keeps the original null value) which leads to the error you see.

Really, the fix is probably just this:

func _process(delta):
    var val = rand.randi_range(1,4)
    if val == 1:
        new_lev = Levi.duplicate()
    elif val == 2:
        new_lev = Levii.duplicate()
    elif val == 3:
        new_lev = Leviii.duplicate()
    elif val == 4:
        new_lev = Leviv.duplicate()