Updating variable problem

I’m making a dropper game that randomly chooses game modes. It is a function that chooses the game mode through math.random() on an array. My problem is that when the function is called more than once, it doesn’t update.

This calls the function:

NewTower(TowerTypes[math.random(1,#TowerTypes)])

and a snippet of code inside the function

print(ChosenTower)
GamemodeText.Text = "Gamemode: "..ChosenTower

When the function is called more than once, the print() prints the random game mode but the GamemodeText’s text still stays the same as the first math.random()'s value.
Example:
First time function is called:

  • math.random() chooses “value”
  • print() prints “value”
  • GamemodeText.Text is changed to “Gamemode: value”

Second time function is called:

  • math.random() chooses “value2”
  • print() prints “value2”
  • BUT GamemodeText.Text is still the same, the value still being “value”

Is there any way to fix it?

Hi there, 2ydro.

So, I think it might be better if you select your random chosen tower, each time WITHIN the function, and pass through the Towers Array, to ensure that you get a different value each time. So, I would do…

local function NewTower(TowerTypes)
   local ChosenTower = TowerTypes[math.random(1,#TowerTypes)]
   return ChosenTower
end
print("GameMode: " NewTower(TowerTypes))

Let me know if this helps!

I’ve tried it before, but it doesn’t work. The math.random() already chooses a random value each time, but it’s the GamemodeText that doesn’t update.

Well, there’s a .Changed function? Create a string value located in Rep Storage.

local ChosenTower = game.ReplicatedStorage.ChosenTower

ChosenTower.Changed:Connect(function(newVal)
    print("GameMode: " .. newVal)
end)

You would run your functions as you normally would but rather than just printing, you would say something along the lines of:

ChosenTower.Value = TowerTypes[math.random(1,#TowerTypes)]

I’ll go ahead and try it out on my end.

So the StringValue changes to the game mode, but it seems that the problem is that if I do ChosenTower.Value it still returns the very first value it had.

You need to post the full code around the issue you are having. The issue is not identifiable from the snippet you provided.