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 fix this if then statement?

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

local Hit = script:waitforchild("Random")

while wait() do
if Hit.Value == true then
print('Hi')
end
if Hit.Value == false then
print('Goodbye')
end
end

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 comment

1

It is suppost to be WaitForChild. Caps do matter in Lua.

1 answer

✓ Accepted answer

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!

local Hit = script:WaitForChild("Random")

Hit.Changed:connect(function()
	if Hit.Value == true then --the `== true` can be omitted here, since `if true == true then` --> `if true then`
		print("Hi")
	else --If it's not true, it must be false!
		print("Goodbye")
	end
end)

If you want to add more variables to check:

local Hit = script:WaitForChild("Random")

Hit.Changed:connect(function()
	if Hit.Value and someOtherValue.Value then
		print("Hi -- someOtherValue is true!")
	elseif Hit.Value then
		print("Goodbye -- someOtherValue is false!")
	else
		print("someOtherValue is unknown!")
	end

	--or, just add another `if` tree:

	if someThirdValue.Value then
		print(1)
	else
		print(2)
	end
end)

2 comments

0

Let's say there were two variables involved, how would I get that to work? Would I have another ".Changed:Connect(function()" line?

0

No need! You can simply add more if trees inside the connected function. I'll edit my answer to include an example.

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