I have made a revolver with a limited amount of bullets in it, and whenever you reload, its supposed to subtract 6 from the ammo. But instead every time the revolver reloads, it subtracts more than its last reload. Here is my code:
if script.Parent.Parent.GranderAmmo.Value>0 then
script.Parent.Parent.Enabled=false
script.Parent.Parent.Handle.Reload:Play()
script.Parent.Parent.Handle.Reload.Ended:Connect(function(sound)
script.Parent.Parent.Enabled=true
script.Parent.Parent.Ammo.Value=6
script.Parent.Parent.GranderAmmo.Value=script.Parent.Parent.GranderAmmo.Value-6
end)
else
script.Parent.Parent.Handle.Empty:Play()
end
Some info:
Ammo is the revolvers currently loaded ammo. GreaterAmmo is the bullets the revolver has left.
if script.Parent.Parent.GranderAmmo.Value>0 then
print("GranderAmmo = " ... script.Parent.Parent.GranderAmmo.Value)
print("Ammo = " ... script.Parent.Parent.Ammo.Value)
script.Parent.Parent.Enabled=false
script.Parent.Parent.Handle.Reload:Play()
script.Parent.Parent.Handle.Reload.Ended:Connect(function(sound)
script.Parent.Parent.Enabled=true
script.Parent.Parent.Ammo.Value=6
script.Parent.Parent.GranderAmmo.Value=script.Parent.Parent.GranderAmmo.Value-6
end)
else
script.Parent.Parent.Handle.Empty:Play()
end
Your script looks ok to me, but my print statements will let you know what the values are when this if segment of code runs. If the prints give a different value than you expect the calculations are skewed by something outside of this segment of code.
Just Found Something Out:
Every time the revolver reloads, it increases the amount that it executes the function that happens after the reload.
I used print to find this.
First reload, it printed Subtraction Executed, but second reload, it printed Subtraction Executed (x2)
Hey, your issue is probably that your Reload.Ended event is duplicating. Basically, everytime your script runs, it will read that line, and it will connect the event again and again everytime it reads, while the previous ones are still connected.
One solution you can apply is to disconnect the event after each use so that it can be reconnected later on when needed, and not duplicated.
This is your current part of the script that causes the problem.
I think if you just replace the :Connect( with :Once( it will be fixed. It’s just like connecting an event, except that it automatically disconnects it after running once.
But moving that event outside of this code block like others have suggested would be better, so you don’t unnecessarily reconnect and disconnect the same event again and again.