Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

"Player is not a valid member of workspace" What is wrong?

function NearestPlayer()
	local Players = game.Players:GetChildren()
	local newMinion = workspace.Minions.newMinion
	local function DistanceList()
		local PlayerDisList = {}
		for i, v in ipairs(Players) do
			local Player = Players[i]
			print(Player) --Prints the correct name when I run it
			local disToPlayer = workspace.Player.Head.Position - newMinion.Head.Position --Error comes out here
			table.insert(PlayerDisList, disToPlayer.magnitude)
		end
		return PlayerDisList
	end
	local function ClosestPlayer()
		local DisList = DistanceList()
		local key, min = 1, DisList[1]
		for i, v in ipairs(DisList) do
			if DisList[i] < min then
				key, min = i, v
			end
		end
		return key
	end
	return ClosestPlayer()
end
return NearestPlayer()

When I print out the variable "Player" it comes out correctly, but when I use the variable elsewhere it seems to not work.

2 comments

0

If my answer worked, please remember to press "Accept Answer"

1

Did TheHospitalDev answer your question? Please click Accept Answer just below the comments section of his post.

1 answer

✓ Accepted answer
function NearestPlayer()
    local Players = game.Players:GetChildren()
    local newMinion = workspace.Minions.newMinion
    local function DistanceList()
        local PlayerDisList = {}
        for i, v in ipairs(Players) do
            local Player = Players[i]
	    local character = Player.Character
            print(Player) 
            local disToPlayer = character.Head.Position - newMinion.Head.Position --You tried to access "Player" in workspace, which is non existant. You would want to access the player's character, 
            table.insert(PlayerDisList, disToPlayer.magnitude)
        end
        return PlayerDisList
    end
    local function ClosestPlayer()
        local DisList = DistanceList()
        local key, min = 1, DisList[1]
        for i, v in ipairs(DisList) do
            if DisList[i] < min then
                key, min = i, v
            end
        end
        return key
    end
    return ClosestPlayer()
end
return NearestPlayer()

1 comment

0

Thank you :)

This discussion is preserved as it was. New answers, comments, and votes are closed.