How to get player from every character in workspace

I am trying to code an explosion shake for my grenade tool, and I want to use events to control when it shakes. The only problem is I need to return a player arg in the fireclient() in order to use the shake, but I have no idea how to do this since my script gets every torso in the workspace to detect how close someone is to handle hit detection and limb loss etc, which I also want to use for handling the screenshake intensity and who is affected by it.

Here is the explosion function:

function Explosion(obj)
	obj.Transparency = 1
	local explosion = Instance.new("Explosion")
	explosion.DestroyJointRadiusPercent = 0
	explosion.BlastRadius = 20
	explosion.Parent = obj
	explosion.Position = obj.Position
	explosion.Visible = true 
	obj.Explode:Play()
	for index, torsos in pairs(workspace:GetDescendants()) do
		if torsos.Name == "Torso" and torsos:IsA("Part") then
			if (torsos.Position - obj.Position).Magnitude < 12.5 then
				local LLeg = math.random(1,2)
				local RLeg = math.random(1,2)
				local LArm = math.random(1,2)
				local RArm = math.random(1,2)
				torsos.Parent.Humanoid:TakeDamage(100)
				game.ReplicatedStorage.Events.GoreEvent:FireAllClients(math.random(4,8), torsos.Position)
				if LLeg == 1 then
					LimbHandler.DamageLimb(torsos.Parent, "Left Leg", math.huge)
				end
				if RLeg == 2 then
					LimbHandler.DamageLimb(torsos.Parent, "Right Leg", math.huge)
				end
				if LArm == 1 then
					LimbHandler.DamageLimb(torsos.Parent, "Left Arm", math.huge)
				end
				if RArm == 2 then
					LimbHandler.DamageLimb(torsos.Parent, "Right Arm", math.huge)
				end
			elseif (torsos.Position - obj.Position).Magnitude < 30 then
				torsos.Parent.Humanoid:TakeDamage(50)
				game.ReplicatedStorage.Events.Shake:FireClient(player, player, 1.5) -- shake intensity
				torsos.Parent.MiscRagdoll.Disabled = false
			end
		end
	end
	wait(2)
	obj.Collision:Destroy()
	obj:Destroy()
end

If you’re looking to obtain a player from a given torso, utilize the Players:GetPlayerFromCharacter() method.

local player = game:GetService("Players"):GetPlayerFromCharacter(torsos.Parent) -- Retrieves the player from the given character (torsos.Parent)
if player then -- Makes sure the player exists
	--Fire your client with the player here
end

A better way of getting every character would be looping through all the players.

for _,player in pairs(game.Players:GetPlayers()) do
    local character = player.Character
    local magnitude = (character.Torso.Position - obj.Position).Magnitude
    if Magnitude <= 12.5 then
        -- Do stuff
    end
end

This will also negate your original issue.

2 Likes