How do I properly run a function at random?

Godot Version

v4.2.1.stable.official [b09f793f5]

Question

I’ve been banging my head trying to figure out how to run a custom function at random.

Here is my code so far.

extends Node3D

var place_block = [place_right(), place_left(), place_front(), place_back()]

func place_right():
var spawn_cube = load(“res://cube.tscn”).instantiate()
spawn_cube.position.x = 1
spawn_cube.position.y = 1
spawn_cube.position.z = 0
spawn_cube.rotation.y = 90
add_child(spawn_cube)

func place_left():
var spawn_cube = load(“res://cube.tscn”).instantiate()
spawn_cube.position.x = -1
spawn_cube.position.y = 1
spawn_cube.position.z = 0
spawn_cube.rotation.y = 30
add_child(spawn_cube)

func place_front():
var spawn_cube = load(“res://cube.tscn”).instantiate()
spawn_cube.position.x = 0
spawn_cube.position.y = 1
spawn_cube.position.z = -1
spawn_cube.rotation.y = 0
add_child(spawn_cube)

func place_back():
var spawn_cube = load(“res://cube.tscn”).instantiate()
spawn_cube.position.x = 0
spawn_cube.position.y = 1
spawn_cube.position.z = 1
spawn_cube.rotation.y = 0
add_child(spawn_cube)

func _timed_mode():
place_block.pick_random()

It’s supposed to spawn a cube randomly at fixed points.
What am I doing wrong here?

You are calling the method in the array, so the initialized value is null for all elements since the methods don’t return anything.

Instead, you need to remove all parentheses from the array declaration, and use this to call one of the array’s values (a Callable) at random:

place_block.pick_random().call()
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.