Making the touched event only run for the player that touches a part

hello all,
I am having an issue where an event that is triggered in a local script happens for all players. This is because the event is the .touched event which triggers for all players. Is there an alternative to the .touched event where the event only triggers for the player that touches an object.

if my explanation is confusing, I just want to know if there is a way to make the .touched event only run for the player that touches an object

2 Likes

You can check if the LocalPlayer’s Character was the one that touched the part by comparing the result you get from calling :GetPlayerFromCharacter() on the Parent of the Instance that touched the part.

This will ensure that the main code inside of the function is only activated on a per-player basis once they are the one that activated the Touched event.

local Players = game:GetService("Players")
local player = Players.LocalPlayer

local part = workspace.Part

part.Touched:Connect(function(itemThatTouchedPart)

    local playerCheck = Players:GetPlayerFromCharacter(itemThatTouchedPart.Parent) -- Checks if a player's Character touched the part

    if playerCheck and playerCheck == player then
--[[ If a player's Character touched the part and if it was by the same player
that has this LocalScript, the condition will be met & the code will continue --]]
    end
end)
4 Likes