Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make script run only if it touches a specific block?

Hi. I'm tying to make a script run only if it touches a specific brick. The current script I have is

 local function onTouch(hit)
	if (hit.Parent.Parent.Parent) then
		print(hit)
	script.Parent.Parent.J.AlignPosition.Enabled = true
	wait(5.3)
	script.Parent.Parent.J.AlignPosition.Enabled = false
	end
end

script.Parent.Touched:connect(onTouch)

I want it so that if it touches a specific other brick, it'll run. Any help will be appreciated. Thanks.

1 answer

✓ Accepted answer

You might be better off using a module which would handle additional code.

Example module:-

local run = false

local function runCode()
	while run do
		-- code
		wait(0.5) -- need a wait in the loop
	end
end

local function stop()
	run = false
end	

return function()
	if run then return end --  no need to run twice
	run = true

	spawn(runCode) -- create a new thread for run
	delay(5.3, stop) -- delay the stop function for 5.3 seconds
end

script:-

-- load module
local run = require([location to module]) -- module passes back a function

script.Parent.Touched:Connect(function(hit)
	run() -- run out code
	-- additional code can be run as we created a thread so this code will not yield
end)

Enabling and disabling scripts is a bad idea as you have no control over how they stop. Using a module should help you a lot in this case. Modules are very usefull but will take time to learn if you have not used them before.

I hope this helps, please comment if you do not understand any parts of the code.

2 comments

0

I'll look in to modules, seems a lot better. Thank you so much!

0

np

This discussion is preserved as it was. New answers, comments, and votes are closed.