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

When I touch the part dissapears but then reappears when I touch again Help?

I have not scripted in a long time and I ran across a problem im making a minigame and I kinda understand my problem I created a function that everytime I touch it it will read what I wrote under the function but I cant think of a way to make it that It only does it once a loop maybe not sure please help me out?

function ontouch()
	local d = 1
if d == 1 then	
function Fall()
   local p = script.Parent
    p.Transparency = 0.1
    wait(0.5)
    p.Transparency = 0.2
    wait(0.5)
    p.Transparency = 0.3
    wait(0.5)
    p.Transparency = 0.4
    wait(0.5)
    p.Transparency = 0.5
    wait(0.5)
    p.Transparency = 0.6
    wait(0.5)
    p.Transparency = 0.7
    wait(0.5)
    p.Transparency = 0.8
    wait(0.5)
    p.Transparency = 0.9
    wait(0.5)
    p.Transparency = 1
    wait(0.2)
    p.CanCollide = false
    end
   Fall()
end
d = 0
end
script.Parent.Touched:connect(ontouch)

1 answer

✓ Accepted answer

##Problem

You're resetting the value of d when the event is finished with execution. Therefore, whenever you touch the brick the initial value of 1 will return to 0 every time.


##Solution

Hold the variable outside of the function. This way when the value of d is 1, the function will know not to execute.


##Efficiency

For a script like this, the line p.Transparency becomes quite redundant and inefficient after a while of copying, pasting, and modifying. The simple solution for this would be to use a numeric for loop.

What a for loop does is for every step (provided you utilize the third argument), or everything, between the first number and the second number the code will execute. For instance if I had for i=1, 10 do, since the step is not defined it is 1 by default. i is a variable for the number the numeric for loop is on. i be 1, then 2, then 3, then 4, so forth until it reaches 10.


##Final Script

local d = 1 --All you have to do is move it out of the function.

function ontouch()
    if d == 1 then  
        function Fall()
            d = 0 --Since the function is already executing, we need to set do to 0.
            local p = script.Parent
            for i=0, 1, .1 do --We are utilizing the step argument,
                --so for every .1 between 0 and 1 the code will run and the variable will change.
                p.Transparency = i
                wait(.2)
            end
            p.CanCollide = false
        end
    Fall()
    end
    
end
script.Parent.Touched:connect(ontouch)

######Hopefully this answered your question, if it did do not forget to hit the accept answer button. If you have any questions, feel free to post them in the comments below.

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