:GetBoundsInPart() problem

I’m currently making a script that will make the player’s walk speed to 3 when the player touches a part inside a folder called “Mud”

The problem I have currently is that I don’t know how I can make the player’s walk speed back to normal when the player is not touching any of the parts in the folder.

script:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character

local MudFolder = workspace.Game:WaitForChild("Mud")

local defaultWalkSpeed = character.Humanoid.WalkSpeed

while wait() do
	for i, parts in pairs(MudFolder:GetChildren()) do
		local mudParts = workspace:GetPartsInPart(parts)
		for i, part in pairs(mudParts) do
			if part.Parent:FindFirstChild("Humanoid") then
				character.Humanoid.WalkSpeed = 3
                --prob need to do something here but idk
			end
		end
	end
end

Using a while true loop to constantly check if the player is touching a mud part might seem convenient, but it impacts performance. Instead, try using the ‘Touched’ and ‘TouchEnded’ events. These events tell you when a part touches or stops touching another part. Using them allows you to tell when a player started or ended touching a part.

Here is the code:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

local MudFolder = workspace.Game:WaitForChild("Mud")

local defaultWalkSpeed = humanoid.WalkSpeed

for _, parts in pairs(MudFolder:GetChildren()) do
        parts.Touched:Connect(function(hit)
            if hit.Parent == character then
                humanoid.WalkSpeed = 3
            end
        end)
        parts.TouchEnded:Connect(function(hit)
            if hit.Parent == character then
                humanoid.WalkSpeed = defaultWalkSpeed
            end
        end)
end

Ohh, I see. I never knew TouchEnded was a thing, Thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.