Return child node randomly crashes

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

I’m having problems with a function that should return a child node, as sometimes works fine and sometimes (50/50) it crashes.

The idea is to get a random child node from a instanced scene according a condition but when it breaks, I get next error:

Invalid get index ‘0’ (on base: ‘Array’).

My code:

Call the function:

azar= pick_random_child()

The function definition:

func pick_random_child():
	var random_id = randi() % $Frutas.get_child_count() #gets random id from child list
	var grupo=$Frutas.get_child(random_id).get_groups() #gets group from chosen child
	if grupo.empty() == true: #if there is no group
		print("array grupo vacio")
	print("grupo[0] es: ",grupo[0], " y used es: ", used)
	#while used.has(grupo[0])==false:
	if used.has(grupo[0]): #if group is in used array
		print("estoy aqui")
		return $Frutas.get_child(random_id)

with prints i’ve realized that function arrives to the return stament.

Any help will be appreciated as i’m completely lost.

:bust_in_silhouette: Reply From: exuin

Your issue is that you don't return from the function after you check if the group is empty so the function attempts to get an index on an empty array. Either put a return statement after the recursive function call or put the rest of the code in an else block.

Thank you for the trick. I’ve didn’t realized about that.
Playing with your advises I still got several nulls I don’t understand, so I’ve avoided recursive loops inside function. Code at last is:

while azar==null:

func pick_random_child():
    	var random_id = randi() % $Frutas.get_child_count()
    	var grupo=$Frutas.get_child(random_id).get_groups()
    	if grupo.empty() == true:
    		return null
    	elif used.has(grupo[0]):
    		return $Frutas.get_child(random_id)
    		return null

It seems working fine.

Thank you very much

heavyathan | 2021-03-14 13:59