select random Node2D from library using data from json file

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

(while I wait to be accepted onto the godot developers forum, thought I would ask)

I want to spawn sprites onto the 2d canvas of my game, but I ALSO want to do this using node names or number names drawn randomly from an external json file–to allow my players to add custom game objects with their own graphics and json edits.

Can anyone recommend how I would go about selecting a random node from the game library as I instance it?

and if that’s even possible by drawing the node’s name based on a string from a json file?

thank you SO much for any ideas or leads!

Don’t know really where to start. What have you done so far?
Random numbers can be got using randi()%20 (or an other value). More information to that here.

Could you save the names and numbers from your json file in a list or a dict or so and then select random items to span them on random locations?

Jowan-Spooner | 2018-12-22 10:54

thanks for the response, Jowan!

and I had figured one way to do it using an array of Node2D scenes/graphics icons:


extends Node2D
var enviroArray =

func _ready():
randomize()
enviroArray.append(preload(“res://Enviro NodeScenes/enviro001.tscn”).instance())
enviroArray.append(preload(“res://Enviro NodeScenes/enviro002.tscn”).instance())
enviroArray.append(preload(“res://Enviro NodeScenes/enviro003.tscn”).instance())
enviroArray.append(preload(“res://Enviro NodeScenes/enviro004.tscn”).instance())
#this will go on to 300 lines, don’t know a quicker way.

func _on_randomEnviroBtn_button_down():
var spriteIcon = enviroArray[randi()% enviroArray.size()]
spriteIcon.position = Vector2(get_viewport().size.x/2, get_viewport().size.y/2)
add_child(spriteIcon)

Ethan | 2018-12-24 19:29

:bust_in_silhouette: Reply From: Jowan-Spooner

well you might have figured out that already but here’s some shorter code (not tested):

extends Node
var spritelist  = []
func _ready():
     #updating the spritelist
     spritelist = create_list()

func get_all_files(path):
    #get all the files you have
    var files = [] 
	var dir = Directory.new()
	dir.open(path)
	dir.list_dir_begin()

	while true:
		var file = dir.get_next()
		if file == "":
			break
		elif not file.begins_with("."):
			files.append(file)
	dir.list_dir_end()
            return files

func create_list():
     #create a list containing actual instances
     var files = get_all_files("res://customsprites")
     var sprites = []
     for file in files:
         sprites.append(load(file).instance())
     return sprites

func get_random_sprite():
     #select and set up a random sprite
     var sprite = spritelist[randi()%len(spritelist)]
     sprite.position = Vector2()
     add_child(sprite)

is this what you were looking for? And what did you want about the names. Could you explain that in more detail?