Vehicle Spawning System not working

Hello, I am currently making a vehicle system that checks a folder and adds all the “pads” which are just parts into a table. Each pad has a value inside determining if it is being touched by a vehicle. The script chooses a random pad that has the being touched value false after the user triggers a proximity prompt.

The problem is it will say there are no more available spots when there are, and if you keep trying to spawn one it eventually works.

local pad = {}
for _, child in ipairs(spawnsfolder:GetChildren()) do
	table.insert(pad, child.Name)
	print(pad)
end


function FindSpawnLocation()
	local randomIndex = math.random(#pad)
	local selectedPad = pad[randomIndex]
	if spawnsfolder[selectedPad].BeingTouched.Value == false then
		print(selectedPad)
		return selectedPad
	end
end





proximityprompt.Triggered:Connect(function(player)
	local SpawnLoc = spawnsfolder[FindSpawnLocation()].Position --line 27
--clone vehicle
end)





Error: invalid argument #2 (string expected, got nil) Line 27

It seems the issue is in the FindSpawnLocation function. It only returns the selected pad if the random one is false. But what if it’s not? Idk if I understood correctly, but I think what you need to do is keep checking for a random index until the being touched value is false. Otherwise, it won’t return anything, which is why the error says it got nil sometimes.

function FindSpawnLocation(): Part
  local selectedPad: Part = nil
  
  while selectedPad == nil do
    local randomIndex = math.random(#pad)
    if not spawnsfolder[pad[randomIndex]].BeingTouched.Value then
        selectedPad = pad[randomIndex]
    end
  end

  return selectedPad
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.