Advertisement
hyperdoxical

Having buttons load random scenes in Godot

Jun 15th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. extends Control
  2.  
  3. var scenes : Array = []
  4. var path_to_scenes : String = "res://scenes"
  5.  
  6. func _ready():
  7. scenes = list_files_in_directory(path_to_scenes)
  8. var v_box_container_instance = VBoxContainer.new()
  9. add_child(v_box_container_instance)
  10. for i in 6:
  11. var button_instance = Button.new()
  12. button_instance.name = "Button" + str(i)
  13. button_instance.text = str(i)
  14. v_box_container_instance.add_child(button_instance)
  15. button_instance.connect("pressed", self, "_on_button_pressed", [i])
  16.  
  17. func load_scene( res ):
  18.  
  19. var scene_instance = load( res ).instance()
  20. get_parent().add_child(scene_instance)
  21.  
  22. queue_free() # may or maynot suit your needs
  23.  
  24. func list_files_in_directory(path):
  25. var files = []
  26. var dir = Directory.new()
  27. dir.open(path)
  28. dir.list_dir_begin()
  29.  
  30. while true:
  31. var file = dir.get_next()
  32. if file == "":
  33. break
  34. elif file.ends_with(".tscn"):
  35. files.append(file)
  36.  
  37. dir.list_dir_end()
  38.  
  39. return files
  40.  
  41. func _on_button_pressed( value):
  42. #print( value ) # will most likely come in handy knowing which button was pressed
  43. load_scene( scenes[int(rand_range(0,scenes.size()))])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement