I’m currently making a game and it requires you to find objects,
Currently, I am trying to make a script that will spawn the actual objects randomly on the map, now this does script does work, but for some reason, it will sometimes not spawn 5, and instead will spawn less (usually it will spawn 2 instead of 5). There are no errors or prints in console at all.
-- Constants
local shovel = game.ServerStorage.Tools.ShovelGround -- Change this to match the name of your shovel object
local mapSize = 100 -- Adjust this value according to your map size
local numberOfShovels = 5 -- Set the number of shovels to spawn
local maxAttempts = 100 -- Maximum attempts to find a suitable position
-- Function to generate random spawn position
local function getRandomPosition()
local position = Vector3.new(
math.random(-mapSize, mapSize),
5, -- Adjust this to control the height of the spawn
math.random(-mapSize, mapSize)
)
return position
end
-- Function to check if the spawn location is clear
local function isClear(position)
local region = Region3.new(position - Vector3.new(1, 1, 1), position + Vector3.new(1, 1, 1))
local parts = workspace:FindPartsInRegion3(region, nil, math.huge)
return #parts == 0
end
-- Function to spawn the shovel
local function spawnShovels()
local shovelsSpawned = 0
for i = 1, numberOfShovels do
local position
local attempts = 0
repeat
position = getRandomPosition()
attempts = attempts + 1
until isClear(position) or attempts >= maxAttempts
if attempts < maxAttempts then
local newShovel = shovel:Clone()
newShovel.Parent = workspace
newShovel:SetPrimaryPartCFrame(CFrame.new(position))
shovelsSpawned = shovelsSpawned + 1
else
warn("Could not find a suitable position for shovel #" .. shovelsSpawned + 1)
end
end
end
-- Call the function to spawn shovels
spawnShovels()
(it’s 1:30 am and my brain is dead so don’t blame me if it’s something easy)