You can try out a popular module named ZonePlus. It’s pretty simple and accurate and a lot of developers use it already. Here’s an example code for achieving this using the ZonePlus module:
local ServerStorage = game:GetService("ServerStorage")
local Zoneplus = require(ServerStorage:WaitForChild("ZonePlus")) -- We get the module
local PlayersInZone = {}
local Container = --part reference goes here
local CF = Container.CFrame
local Size = Container.Size
local Zone = Zoneplus.fromRegion(CF, Size) -- We have our zone
local DamageDelay = 3 -- players in zone get damaged every 3 seconds
task.spawn(function()
while task.wait(DamageDelay) do
for _, player in ipairs(PlayersInZone) do
local Damage = --Damage to deal here, for random damage, use math.random().
local Character = player.Character or player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
Humanoid:TakeDamage(Damage)
end
end
end)
Zone.playerEntered:Connect(function(player)
table.insert(PlayersInZone, player)
end)
Zone.playerExited:Connect(function(player)
if table.find(PlayersInZone, player) then table[player] = nil end
end)