Advertisement
XeroXipher2022

Loading NPC Data from JSON File (Dictionary)

Dec 7th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## NPCs.gd
  2.  
  3. extends Entity
  4.  
  5. #const file_path = "res://Game/Data/Enemies.json"
  6.  
  7. var enemy_data_dict: Dictionary = {}
  8.  
  9. func _ready() -> void:
  10.     pass
  11.  
  12. func load_enemy_data(file_path: String) -> void:
  13.     var file = FileAccess.open(file_path, FileAccess.READ)
  14.     if file:
  15.         var json_data = JSON.parse_string(file.get_as_text())
  16.         if json_data.error == OK:
  17.             if typeof(json_data.result) == TYPE_DICTIONARY:
  18.                 enemy_data_dict = json_data.result
  19.                 print("Loaded Enemy Data Successfully")
  20.                 file.close()
  21.             else:
  22.                 print("JSON Error: Parsed Data is not a Dictionary")
  23.                
  24.         else:
  25.             print("Error parsing JSON: ", json_data.error_string)
  26.         file.close()
  27.     else:
  28.         print("Failed to open File: ", file_path)
  29.    
  30. func get_enemy_data(enemy_key: String) -> Dictionary:
  31.     #if enemy_key in enemy_data_dict:
  32.     return enemy_data_dict.get(enemy_key, {})
  33.    
  34.     #return {}
  35.  
  36.  
  37. ## if json_data.error == OK: ## In the above code is where the error is.
  38. ## The Error is a StackTrace Error: "Invalid access to property or key 'error' on a  base object of type 'Dictionary"
  39. ## The following code is where load_enemy_data() is called and is also throwing an error but I think the problem is in the above code. ##
  40.  
  41. ## Enemy_Screen.gd
  42.  
  43. extends Entity
  44.  
  45. @onready var enemy_ui = preload("res://Scripts/Entities/EnemyScript.gd").new()
  46. @onready var npc_manager = preload("res://Scripts/Entities/NPCs.gd").new()
  47.  
  48. func _ready() -> void:
  49.     npc_manager.load_enemy_data("res://Game/Data/Enemies.json") ##THIS IS WHERE THE ERROR IS IN THIS FILE
  50.    
  51.     if typeof(npc_manager.enemy_data_dict) == TYPE_DICTIONARY and npc_manager.enemy_data_dict.size() > 0:
  52.         var keys = npc_manager.enemy_data_dict.keys()
  53.         enemy_ui.select_enemy(keys[0])
  54.     else:
  55.         print("No NPC's Available")
  56.        
  57. func select_next_enemy():
  58.     var keys = npc_manager.enemy_data_dict.keys()
  59.     var current_index = keys.find(enemy_ui.selected_enemy_key)
  60.     if current_index != -1:
  61.         var next_index = (current_index + 1) % keys.size()
  62.         enemy_ui.select_enemy(keys[next_index])
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement