I made a simple script that takes a folder I have in replicated storage and grabs a random enemy from that folder and spawns it on the attached part location. I have about 40 NPCs in this folder in replicated storage and about 25 of these parts scattered across the map. I want random NPCs at these locations so its not always the same ones in the same places. The issue is:
It spawns the same NPC upon map creation everywhere. Its a random enemy from the folder on game load but it spawns the same enemy at every single part. The code is very simply and I do have an altered code for each part. For example for enemy spawn #2 would be
local NPCS = game.ReplicatedStorage.Enemies:GetChildren()
local ChosenNPC = NPCS[math.random(#NPCS)]:Clone()
ChosenNPC.HumanoidRootPart.Position = workspace.EnemySpawns.Spawn1.Position
ChosenNPC.Parent = workspace
Any idea why its randomising it on creation but the same NPC is going to every part? Thanks for any help!
I think it might be because its calling the same “chosenNPC” for each script and its acting weird? I don’t know how to make that different or do I need to alter all 25 parts and change the function name?
Put your script inside a while loop or something, so it keeps changing the ChosenNPC everytime it’s going to spawn an enemy.
Can you also please show the full code?
local NPCS = game.ReplicatedStorage.Enemies:GetChildren()
local ChosenNPC = NPCS[math.random(1, #NPCS)]
print(ChosenNPC)
if ChosenNPC then
ChosenNPC:Clone()
ChosenNPC.HumanoidRootPart.Position = workspace.EnemySpawns.Spawn1.Position
ChosenNPC.Parent = workspace
ChosenNPC:MakeJoints()
end
game > ReplicatedStorage > Enemies
Should have all of the enemy models
Like I said, very simple script I just attached to a parts, named them Spawn 1 through 25 and changes the spawn name in the script then scattered around. Thanks for the idea. I will research loops. Very new to scripting.
Basing off @JackscarIitt 's code, i think we have found the solution:
local NPCS = game.ReplicatedStorage.Enemies:GetChildren()
while wait(5) do
local ChosenNPC = NPCS[math.random(1, #NPCS)]
local ChosenSpawn = math.random(1, 25)
print(ChosenNPC)
print(ChosenSpawn)
if ChosenNPC then
ChosenNPC:Clone()
ChosenNPC.HumanoidRootPart.Position = workspace.EnemySpawns:FindFirstChild("Spawn"..ChosenSpawn).Position
ChosenNPC.Parent = workspace
ChosenNPC:MakeJoints()
end
end
If you only provide 1 parameter for math.random, it assumes that you that the first parameter is 1. So saying math.random(10) is the same as saying math.random(1,10)