How to "lock" a variable?

I have been trying to reduce the music in my game with a while loop, however since you can change the volume of the music as a player, the amount of volume decrease per tick needed to hit volume 0 is different depending on the start volume.

Ideally I would just write:

startVol = game.SoundService.sound.Volume
game.SoundService.sound.Volume -= startVol/tickAmount

, but of course the variable changes each time it ticks, so it ends up not working.

So my question is if there is a way to lock the variable so it cannot be changed after being assigned.

Can you please include all of your code? If you variable is declared inside of a loop it will be frequently updated with the new value

Yes it is inside of a loop

local function playClick()
	while script.Parent.Parent.darken.Transparency >= 0 do
		wait(0.01)
		script.Parent.Parent.darken.Transparency -= 0.02
		game.SoundService.menuMusic.Volume -= 0.666/50
	end
end

playB.MouseButton1Click:Connect(playClick)
1 Like

If you declare your variable outside of your loop it should work. Here is an example:

local bName = Workspace.Part.Name

while true do
Workspace.Part.Name = math.random(1,5)
end

The variable bName in this instance will get the name of the part BEFORE it is changed.

while true do
local bName = Workspace.Part.Name
Workspace.Part.Name = math.random(1,5)
end

In this paragraph, the variable bName will update every single time this loop runs to get the updated version of the name.

1 Like

I figured it out just before you replied. For some reason I thought it would update the variable even while in the loop, but of course the loop locks the script in those lines (as I understand it now).

local function playClick()

local startVol = game.SoundService.menuMusic.Volume

while script.Parent.Parent.darken.Transparency >= 0 do
	wait(0.01)
	script.Parent.Parent.darken.Transparency -= 0.02
	game.SoundService.menuMusic.Volume -= (startVol/100)*2
	print(startVol)

end

end

Looks good! Good luck with your game :slight_smile:

1 Like

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