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

How do I do Block math? (continued)

number1 = script.Parent.Name; --The name is 0
number2 = 1;
number3 = 10;
number4 = 40;
number5 = 250;

function onTouched(hit)   --Function 1
number1 = script.Parent.Name
	print(number1+number2) 
	script.Parent.Name = (number1+number2)
	wait(0.2)
	print"ahh" 
end

script.Parent.Touched:connect(onTouched)

function math()   --Function 2
if script.Parent.Name == 50 then
	script.Parent.TopSurface = "Studs"
end

Got two issues, the tutorial tells me to do "if 1==1 then" and that will work, how come the 2nd function won't work? Two things, How do I put a pause between when Function 1 can operate, because it will just occur whenever, the "wait(0.2)" doesn't delay when it acts. And, how do I make Function 2 work?

1 answer

✓ Accepted answer

For function 1, it will run whenever the part is touched, and because of the way Lua works, multiple threads running the function can happen if multiple collisions are detected. To solve this, we have (what people like to call) debounce.

number1 = script.Parent.Name; --The name is 0
number2 = 1;
number3 = 10;
number4 = 40;
number5 = 250;

debounce = false --Here's debounce, which is initially false.

function onTouched()
	if debounce == true then return end --Don't run the function if debounce is true, otherwise
	debounce = true --Set debounce to true so the function can't run until we set it back to false.
    print(number1+number2) --Continue with the function.
    script.Parent.Name = (number1+number2)
    wait(0.2)
    print "ahh" 
	debounce = false --We did what we needed, so we set debounce back to false.
end

script.Parent.Touched:connect(onTouched)

Function 2 is not running simply because you never called it; it's just sitting there waiting to be called. You need to call the function, like so:

function math()
if script.Parent.Name == "50" then --Since names are strings, we enclose them in single or double quotation marks.
    script.Parent.TopSurface = "Studs"
end

math() --Actually call, or run, math

Full script:

number1 = script.Parent.Name
number2 = 1;
number3 = 10;
number4 = 40;
number5 = 250;

debounce = false

function math()
	if script.Parent.Name == "50" then
		script.Parent.TopSurface = "Studs"
	end
end

function onTouched()
	if debounce == true then return end
	debounce = true
	number1 = script.Parent.Name
	print(number1+number2) 
	script.Parent.Name = (number1+number2)
	wait(0.2)
	print "ahh"
	math()
	debounce = false
end

script.Parent.Touched:connect(onTouched)

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