So I have this cut section of my code, which errors because 'location' is continously nil. How would I update the location to actually make the bit of code function as intended?

function randomLocation()
    local parts = game.Workspace.Tier1:GetChildren()
    if #parts > 0 then
        random = parts[math.random(1, #parts)]
    end
    return random
end

function getPosition()
	local parts = game.Workspace.Tier1:GetChildren()
    if #parts > 0 then
    	loc = randomLocation()
	end
	return loc
end

local location = getPosition()

Tool = script.Parent.Parent

hum.Changed:Connect(function()
	--while true do wait(0.1)
		if hum.Health > 0 then
			--local parts = game.Workspace.Tier1:GetChildren()
    		--if #parts > 0 then
			if location ~= nil then
			getPosition() print'got pos'
			local location = getPosition().Position
			if game.Workspace.Tier1:FindFirstChild("Chest") then
				local head = Character:FindFirstChild("Head") or Character:WaitForChild("Head")
				local distance = (head.Position - location).magnitude 

4 comments

1

the # parts could be 0 or you could do " return loc or 'No Parts' "

0

and see if 'No Parts' gets returned

0

is "random" an undefined variable

0

@the8bitdude11 I know that because it's nil, but how would I fix that? I've been tolk that my loc variable is out of scope, but I'm unsure where to place it to correct the code(?)