Could I use something other than elseif?

Hello I am a new scripter and I want to know if with this bit of code if anyone could give some advice for making the code look a lot less bloated. Thanks :slight_smile:

	if Textchance3 == 1 then 
		script.Parent.W1.Visible = true
		wait(0.5)
		script.Parent.W1.Visible = false
	elseif Textchance3 == 2 then 
		script.Parent.W2.Visible = true
		wait(0.5)
		script.Parent.W2.Visible = false
	elseif Textchance3 == 3 then 
		script.Parent.W3.Visible = true
		wait(0.5)
		script.Parent.W3.Visible = false
	elseif Textchance3 == 4 then
		script.Parent.W4.Visible = true
		wait(0.5)
		script.Parent.W4.Visible = false
	elseif Textchance3 == 5 then
		script.Parent.W5.Visible = true
		wait(0.5)
		script.Parent.W5.Visible = false
	end

Try using functions to make the code shorter.

3 Likes

Well you could do this:

for i = 1, 5 do
    if Textchance3 == i then
           local L = script.Parent[“W”..i]
           L.Visible = true
           task.wait(0.5)
           L.Visible = false
      end
end

If you want an explanation, this for loop (for i = 1, 5 do) runs 5 times. i is equal to 1. Each time it runs that if statement, i is incremented (it goes up) by 1; so i becomes 2 and so on until it becomes 5.

sorry if the explanation isn’t the best, just search up “for loop Roblox tutorial” and you’ll find a better explanation

4 Likes

That also works, lol, I didn’t think about it :man_shrugging:

2 Likes

To expand with my idea and @010DevX101’s idea, you can pair the for loop and a function like so:

local function check(number)
     if Textchance3 == number then
          local L = script.Parent:FindFirstChild(“W”..number)
          L.Visible = true
          task.wait(0.5)
          L.Visible = false
     end
end

for i = 1, 5 do
     check(i)
end

It’s basically the same thing as the other one but I’m using a function to check instead of straight up putting the code in the for loop

3 Likes

This actually worked! I just gotta do this for the multiple other elseif atrocities in my code!
Cheers!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.