So I am trying to make an area-specific NPC spawning. I have different NPCs set up for different areas.
This is my Area setup
And this is the NPC set up for each area. (The NPCs are in the specific folders)
--// Variables local replicatedStorage = game:GetService("ReplicatedStorage") local AreasFolder = game:GetService("Workspace"):WaitForChild("Areas") local AreaNPCsFolder = replicatedStorage:WaitForChild("AreaNPCs") local AreaNPCs = {} for _, Area in pairs(AreasFolder:GetChildren()) do table.insert(AreaNPCs, Area.Name) local NPCs = AreaNPCsFolder:FindFirstChild(Area):GetChildren() table.insert(AreaNPCs[Area], NPCs.Name) end
Basically I want the tabled to be formated as shown:
local AreaNPCs = { ["Spawn"] = {NPC Names Go Here}, ["Lava Hot Springs"] = {NPC Names Go Here}, ["Nuclear Wasteland"] = {NPC Names Go Here}, ["VIP"] = {NPC Names Go Here} }
I am quite unsure of what's wrong with this so anything helps.
The :GetChildren() method of Instance
returns an array first-descendant objects. As you do with creating dictionary references for each "area", you must iterate through each individual NPC and append their names respectively:
--###----------[[SERVICES]]----------###-- local ReplicatedStorage = game:GetService("ReplicatedStorage") --###----------[[VARIABLES]]----------###-- local NPCSpawnAreas = workspace.Areas local KnownAreaNPCs = ReplicatedStorage.AreaNPCs local AreaNPCArray = {} --###----------[[LOGIC]]----------###-- for _, Area in pairs(NPCSpawnAreas:GetChildren()) do print("Traversing: \""..Area.Name.."\"") --------------- local AreaNPCs = KnownAreaNPCs:FindFirstChild(Area.Name) if (AreaNPCs) then --------------- AreaNPCArray[Area.Name] = {} --// Initialize the dictionary reference/array. --------------- print("Allocated dictionary index \""..Area.Name.."\"\n") --------------- for _, NPC in pairs(AreaNPCs:GetChildren()) do --------------- print("Added NPC name \""..NPC.Name.."\" to dictionary index \""..Area.Name.."\"") --------------- table.insert(AreaNPCArray[Area.Name], NPC.Name) end --------------- print("\n") end end
I can assure you that the program is performing the requested task. I recreated the conditions of your game with line-debugging to visually prove this:
Asset outlines can be found here: Workspace folders, ReplicatedStorage folders.
Output confirmation can be found here.
Additionally, I've also adjusted the code above with the necessary print statements.
I actually just got it working.
--// Variables local replicatedStorage = game:GetService("ReplicatedStorage") local AreasFolder = game:GetService("Workspace"):WaitForChild("Areas" local AreaNPCsFolder = replicatedStorage:WaitForChild("AreaNPCs") local AreaNPCs = {} --// Main for _, Area in pairs(AreaNPCsFolder:GetChildren()) do table.insert(AreaNPCs, Area) local SelectedArea = Area local NPCs = Area:GetChildren() table.insert(AreaNPCs, NPCs) end
Thanks for anyone who took a look at this post. I was just trying stuff out and got it working.