Code to pause / resume physics does not work correctly

Hi, I’m trying to make a button that can pause and resume physics. When I press the button the physics pause correctly, but then it does not resume.

local lastState = {}

local function TogglePhysics(Pause: boolean)
	if Pause then
		for i, instance in pairs(workspace:GetDescendants()) do
			if instance:IsA("BasePart") and not instance:IsA("Terrain") then
				lastState[i] = instance.Anchored
				instance.Anchored = true
			end
		end
	elseif not Pause then
		for i, instance in pairs(workspace:GetDescendants()) do
			if instance:IsA("BasePart") and not instance:IsA("Terrain") then
				if lastState[i] then
					instance.Anchored = lastState[i]
				end
			end
		end
		table.clear(lastState)
	end
end

your problem comes from this line

if lastState[i] then
   instance.Anchored = lastState[i]
end

what it should be instead is

if lastState[i] ~= nil then
	instance.Anchored = lastState[i]
end

Also I would recommend changing your lastState table to a dictionary where every index is the instance who’s state you’re storing. It would also mean that for unpausing your physics you’d only need to loop through your lastState table instead of your entire workspace descendants again meaning you could get rid of your if lastState[i] then check!

1 Like