I've got a button, and a ClickDetector, but what I want to happen is when you click the part, it changes a surface gui's text inside the part to the next destination.
local destinations = { "Dest1"; "Dest2"; "Dest3"; "Dest4"; "Dest5"; } script.Parent.MouseClick:connect(function() for _, r in ipairs(destinations) do script.Parent.Parent.TextThing.TextLabel.Text = destinations[_] end end)
But it only functions once. And also how would I make it so it goes from dest 1 to dest 5 and back again, but with the ability to add more destinations?
Numbers!
I hate math
So, I'll forgive you for having that redundant indexing in a loop that already gives you a value for the key. What you want to do is keep the current index outside of the loop, and wrap it around. Simple.
local destinations = { "Dest1"; "Dest2"; "Dest3"; "Dest4"; "Dest5"; } local i = 1; script.Parent.MouseClick:connect(function() i = i%5+1 -- Wrap and increment. In that order. -- Yes, Lua and I have a bad relationship. script.Parent.Parent.TextThing.TextLabel.Text = destinations[i] -- Gross naming btw :c end)
It does work several times, except you loop through all the destinations and leave the text as the final one. You would want to keep track on index and increase it every time the function fires.
local destinations = { "Dest1"; "Dest2"; "Dest3"; "Dest4"; "Dest5"; } local index = 1 script.Parent.MouseClick:connect(function() -- Use the defined index script.Parent.Parent.TextThing.TextLabel.Text = destinations[index] -- This formula would get modulus of index, in order to keep it within the limits -- If index will be equal to #destination(amount of table elements) then you would get back 0 and so on index = index%#destinations+1 end)
Make it so that every time the player clicks the button, a counter
is incremented. Whenever that counter
goes above 5
(which is the number of indices in destination
, set it back to 1
.
A quick and simple way of making it go back to 1
every time if goes over time is to use the modulo %
operator. The modulo operator gets the remainder of a division (i.e. 7%5
evaluates to 2
).
local counter = 1 -- *clicks button* counter = counter%5 + 1
So what's happening?
I initialized the counter to 1. This is because the first index in an array is always 1.
Whenever I click the button, I first use the modulo operator on counter
(so that, when it is currently 5, it rolls back to 0)
Lastly, I add 1 to counter
.
If I were to print the values of counter
every time I click the button, it would appear like this:
1 2 3 4 5 1 2 3 4 5 ...
This pattern would carry on forever. Your final script would appear like this:
local destinations = { "Dest1"; "Dest2"; "Dest3"; "Dest4"; "Dest5"; } local counter = 1 script.Parent.MouseClick:connect(function() counter = counter%5 + 1 script.Parent.Parent.TextThing.TextLabel.Text = destinations[counter] -- and finally, set the Text end)