Random zombie spawn script not working

  • What does the code do?
    This script spawns zombies into parts called “ZombieSpawn”
  • What potential improvements have you considered?
    I tried using math.random, but it would just give me an error
  • How (specifically) do you want to improve the code?
    I would like the script to pick a random ZombieSpawn part and spawn one zombie on it rather than spawn a zombie on every part at once
local spawns = script.Parent
local Enemies = script.Parent.Parent.Enemies

local spawntime = 15

while true do
	wait(spawntime)
	for _, spawn in pairs(spawns:GetChildren()) do
		if spawn:IsA("BasePart") then
			local enemyCopy = game.ReplicatedStorage['Zombie']:Clone()
			enemyCopy.Parent = game.Workspace.Enemies
			enemyCopy.HumanoidRootPart.CFrame = CFrame.new(spawn.Position)
		end
	end
end

That can be done using something like this

local spawns = script.Parent:GetChildren()

local spawntime = 15

while true do
	task.wait(spawntime)
	local randomSpawn = spawns[math.random(#spawns)]
	
	local enemyCopy = game.ReplicatedStorage['Zombie']:Clone()
	enemyCopy.Parent = workspace.Enemies
	enemyCopy.HumanoidRootPart.CFrame = CFrame.new(randomSpawn.Position)
end

It’s likely your error was because you forgot to use the random number of math.random to get a part from the table GetChildren gives

Thanks! This helped alot, but after I tested it a few times, there was an error in the output that read:
Position is not a valid member of Script “Workspace.EnemySpawns.SpawnZombie”

Oh there’s a script in that folder? In that case, what I would do in your case is that you make a table variable, loop through the enemy spawns folder, check if the spawn is a basepart, and insert it to the table and use that instead

something like this

local spawnsFolder = script.Parent:GetChildren()
local Enemies = script.Parent.Parent.Enemies

local spawntime = 15

local spawns = {}

for _, spawn in ipairs(spawnsFolder) do
	if not spawn:IsA("BasePart") then
		continue
	end
	table.insert(spawns, spawn)
end

while true do
	task.wait(spawntime)
	local randomSpawn = spawns[math.random(#spawns)]
	
	local enemyCopy = game.ReplicatedStorage['Zombie']:Clone()
	enemyCopy.Parent = workspace.Enemies
	enemyCopy.HumanoidRootPart.CFrame = CFrame.new(spawn.Position)
end

It says Workspace.EnemySpawns.SpawnZombie:21: attempt to index function with ‘Position’
Ill try setting the scripts parent to workspace instead

I think it may be cause i forgot to change the spawn in

enemyCopy.HumanoidRootPart.CFrame = CFrame.new(spawn.Position)

To randomSpawn

1 Like

Thanks for the help! The script works as intended and there are no errors!

1 Like