Hello, I want to create an area where a player is given an item upon entering, and takes the item away after leaving that area. However, my code does nothing so far and I can’t see why.
The red semitransparent part is the area I’m referring to
I’ve tried to use .Touched and Region3, but .Touched is incredibly hard to work with and from what I’ve heard all Region3 functions have been deprecated. Please help me identify the issue/s in my code!
local area = script.Parent --red semitransparent part
local sword = game.ServerStorage.ClassicSword
local currentParts = {}
for i, v in ipairs(game.Players:GetPlayers()) do
if v.Character then
table.insert(currentParts, v.Character)
end
end
local cf = area.CFrame.Position
local v3 = Vector3.new(area.Size.X, area.Size.Y, area.Size.Z)
local params = OverlapParams.new()
params.FilterDescendantsInstances = {currentParts}
while wait() do
local inArea = workspace:GetPartBoundsInBox(cf, v3, params)
for i, plr in pairs(inArea) do
if plr:FindFirstChild("ClassicSword")[nil] then
local clone = sword:Clone()
clone.Parent = plr
else return end
if table.find(currentParts, plr)[nil] then
plr:FindFirstChild("ClassicSword"):Destroy()
end
end
end
local player_parts = {} -- the table never refreshes causing the parts to never load
while task.wait() do
player_parts = {}
for _, player in ipairs(Players:GetPlayers()) do
local character = player.Character
if character then
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.Health > 0 then -- check if the player isn't dead
local descendants = character:GetDescendants()
for i = 1, #descendants do
if descendants[i]:IsA("BasePart") then
table.insert(player_parts, descendants[i])
end
end
else
local sword = player.Backpack:FindFirstChild("ClassicSword")
if sword then
sword:Destroy()
end
end
end
end
overlapParams.FilterDescendantsInstances = player_parts
local parts: { BasePart } = workspace:GetPartsBoundsInBox(area.CFrame, area.Size, overlapParams)
for _, part in ipairs(parts) do
if table.find(player_parts, part) then
local model = part:FindFirstAncestorWhichIsA("Model") -- ive been trying to put people onto this method of getting characters
if model then
local humanoid = model:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.Health > 0 then
local player = Players:GetPlayerFromCharacter(model)
if player then
sword:Clone().Parent = player.Backpack
end
end
end
end
end
for _, part in ipairs(player_parts) do
if not table.find(parts, part) then
local model = part:FindFirstAncestorWhichIsA("Model")
if model then
local player = Players:GetPlayerFromCharacter(model)
if player then
local sword = player.Backpack:FindFirstChild("ClassicSword")
if sword then sword:Destroy() end
end
end
end
end
end