How can I optimize this script but still keep it simple?

How can I make a script that detects if a player is in a zone but without it firing a bunch of times?
This script gives me a lot of prints in the output every time the player moves while in the zone.

local Zone = script.Parent
local Players = game:GetService("Players")

Zone.Touched:Connect(function(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildOfClass("Humanoid")

    if humanoid then
        local player = Players:GetPlayerFromCharacter(character)
        if player then
            -- Player entered the zone
            print(player.Name .. " entered the zone")

            player.multi.value = 5

        end
    end
end)

Zone.TouchEnded:Connect(function(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildOfClass("Humanoid")

    if humanoid then
        local player = Players:GetPlayerFromCharacter(character)
        if player then
            -- Player exited the zone
            print(player.Name .. " exited the zone")

            player.multi.Value = 1

        end
    end
end)

How about you check if a player is already in the zone?

Assuming Zone is some sort of part representing a region, one approach would be checking if the player is inside some zone when required, instead of listening to .Touched.

local Zone = workspace:WaitForChild("Zone")

-- Used to filter for only the specific player we're looking for.
local ZoneFilter = OverlapParams.new()
ZoneFilter.FilterType = Enum.RaycastFilterType.Include 

function IsInsideZone(player)
	local RootPart = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
	if not RootPart then
		return false
	end
	ZoneFilter.FilterDescendantsInstances = { RootPart }
	return #workspace:GetPartsInPart(Zone, ZoneFilter) > 0
end

Where Zone is some part of Workspace that represents the zone.

The IsInsideZone function returns true if the player is inside the zone, otherwise false.

Then, you could either run this function in a loop for all players or, whenever you use multi.value, you can instead query if the player is within the zone or not on the fly!

Hope this helps!

1 Like