Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How do I fix this if then statement?

Asked by 10 years ago

So this if then statement is supposed to detect a certain value. However, I want it to do something else when the value changes.

01local Hit = script:waitforchild("Random")
02 
03while wait() do
04if Hit.Value == true then
05print('Hi')
06end
07if Hit.Value == false then
08print('Goodbye')
09end
10end

I want the script to do something else once the value changes. How would I make the script do this? Can someone please help me?

1
It is suppost to be WaitForChild. Caps do matter in Lua. woodengop 1134 — 10y

1 answer

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago

Continent is correct, you should be using WaitForChild and not waitforchild.

To catch when an Value object is changed, use the Changed event. You can also make that if statement more efficient by using else instead of a second if!

1local Hit = script:WaitForChild("Random")
2 
3Hit.Changed:connect(function()
4    if Hit.Value == true then --the `== true` can be omitted here, since `if true == true then` --> `if true then`
5        print("Hi")
6    else --If it's not true, it must be false!
7        print("Goodbye")
8    end
9end)

If you want to add more variables to check:

01local Hit = script:WaitForChild("Random")
02 
03Hit.Changed:connect(function()
04    if Hit.Value and someOtherValue.Value then
05        print("Hi -- someOtherValue is true!")
06    elseif Hit.Value then
07        print("Goodbye -- someOtherValue is false!")
08    else
09        print("someOtherValue is unknown!")
10    end
11 
12    --or, just add another `if` tree:
13 
14    if someThirdValue.Value then
15        print(1)
16    else
17        print(2)
18    end
19end)
0
Let's say there were two variables involved, how would I get that to work? Would I have another ".Changed:Connect(function()" line? CoolJohnnyboy 121 — 10y
0
No need! You can simply add more `if` trees inside the connected function. I'll edit my answer to include an example. adark 5487 — 10y
Ad

Answer this question