Could I do this anything better? (Touch script) [READ FOR MORE INFO]

Hello! I am currently doing a code in which Npcs on a map (an image GUI). There are many scripts like this:

Local VentsMap = script.Parent
   function Vent1A(hit)
    if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
       VentsMap.Vent1A.Visible = true
    end
end

game.Workspace.Vent1A:Connect(Touched)

Imagine the same but it does the opposite and it’s with OnTouchEnded.

Imagine the code but with B, and C, and D, and E…
Yeah, basically this goes on a bit.

Is there any ways I could improve this and simplify the code and not make use too much stuff (to make my pc burn).

If there’s any confusion please tell me and I’ll add more info.

Thanks for reading!

1 Like

Maybe try adding a folder containing the vents and then looping through that folder, like this?

local VentsMap = script.Parent

local VentsFolder = workspace.VentsFolder

for x,Vent in pairs(VentsFolder:GetChildren()) do

	function VentHit(hit)
		if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
			VentsMap[Vent.name].Visible = true
		end
	end

	Vent.Touched:Connect(VentHit)

end
1 Like

Thank you so much! I am a but new to scripting, I know basics but this is a HUGE thing that I will usually use.

Just a suggestion on this code, make sure that you leave your functions outside of the for loop. Otherwise you just end up redefining them again and again which takes up more memory

1 Like

Thanks for the suggestion.

Do you think this would be more optimal?

local VentsMap = script.Parent

local VentsFolder = workspace.VentsFolder

function VentHit(hit,Vent)
		if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
			VentsMap[Vent.name].Visible = true
		end
end

for x,Vent in VentsFolder do

	Vent.Touched:Connect(function(hit) 
		VentHit(hit,Vent)
	end)

end
1 Like