Need help optimizing this code

So I wrote a simple script that creates a linear velocity when a part touches the part, like this:


The issue is, that you can see the output, and it shows hundreds of touches and touchEnds, but this is only for the big transparent part.
Whenever it touches a part, it creates a linear velocity, when it ends, it destroys it.

Maybe even help me keeping the floating parts steady?

I have thought of region3’s, but they still boggle my mind on how to use them.

Code:

local part = script.Parent

part.Touched:Connect(function(part1)
	print("touched")
	local wee = Instance.new("LinearVelocity")
	local atta1 = Instance.new("Attachment")
	atta1.Parent = part
	local atta0 = Instance.new("Attachment")
	atta0.Parent = part1
	wee.Attachment0 = atta0
	wee.Attachment1 = atta1
	wee.RelativeTo = Enum.ActuatorRelativeTo.Attachment1
	wee.Parent = part
	wee.MaxForce = 2500
	wee.VelocityConstraintMode = Enum.VelocityConstraintMode.Line
	wee.LineVelocity = -50
	part.TouchEnded:Connect(function()
		print("ended")
		wee:Destroy()
		atta1:Destroy()
		atta0:Destroy()
	end)
end)

1 Like

It’s not showing hundreds of touches, only of touchEnds.
The reason is that each time a part touches the region, it creates a new touchEnded connection, which lingers forever and does nothing because the things it destroys are already destroyed.

The above reply has the right idea (keep a list of parts currently touching the region), but:

  • A part already can’t touch the region again until it has stopped touching it, therefore that addition is useless;
  • The next time any part stops touching the region, all of the parts will fall down.
local part = script.Parent
local touching = {}

part.Touched:Connect(function(part1)
	print("touched")
	local wee = Instance.new("LinearVelocity")
	local atta1 = Instance.new("Attachment")
	atta1.Parent = part
	local atta0 = Instance.new("Attachment")
	atta0.Parent = part1
	wee.Attachment0 = atta0
	wee.Attachment1 = atta1
	wee.RelativeTo = Enum.ActuatorRelativeTo.Attachment1
	wee.Parent = part
	wee.MaxForce = 2500
	wee.VelocityConstraintMode = Enum.VelocityConstraintMode.Line
	wee.LineVelocity = -50
	touching[part1] = wee
end)

part.TouchEnded:Connect(function(part1)
	-- if touching[part1] == nil then return end -- this is commented out because it should never happen. if it does happen and you don't want to see the errors, then uncomment it
	print("ended")
	local wee = touching[part1]
	wee.Attachment0:Destroy()
	wee.Attachment1:Destroy()
	wee:Destroy()
	touching[part1] = nil
end)

You can also eliminate the touching table by naming your LinearVelocity in some unique way and using part1:FindFirstChild("name of your LinearVelocity") instead of touching[part1].

1 Like

Do keep in mind that printing at this rate causes a lot of lag. I’d recommend removing the print calls before looking into the necessary optimisations.

You should also take a look at this post.