Not sure if this is a bug or my code. When I reload the first time, the Mag is cloned only once, but when I reload the second time two Mags falls out…? The number of Cloned Mag that falls out depends on the number of times you have reloaded. This function is called by ContextActionService.
local gun = script.Parent
local CAS = game:GetService("ContextActionService")
local Debris = game:GetService("Debris")
--//States
local aiming = false
local shooting = false
local reloading = false
local canshoot = true
--//Parts of gun
local Mag = gun:WaitForChild("Mag")
--//Load Animations
local Reload = Animations:WaitForChild("Reload")
local ReloadAnim = Humanoid:LoadAnimation(Reload)
--//Reload
local function Reload(actionName, InputState, InputObj)
if InputState == Enum.UserInputState.Begin then
if reloading then return end
shooting = false
canshoot = false
reloading = true
AimAnim:Stop()
ReloadAnim:GetMarkerReachedSignal("MagReloadStart"):Connect(function()
Mag.Transparency = 1
local prop = Mag:Clone()
prop.Transparency = 0
local children = prop:GetChildren()
for i = 1, #children do
children[i]:Destroy()
end
prop.CanCollide = true
prop.Parent = workspace
Debris:AddItem(prop)
end)
ReloadAnim:GetMarkerReachedSignal("MagReloadEnd"):Connect(function()
Mag.Transparency = 0
end)
ReloadAnim:Play()
wait(ReloadAnim.Length)
reloading = false
canshoot = true
end
end
--//Gun Equipped
gun.Equipped:Connect(function()
--//Convert Weld to Motor6D
event:FireServer(gun.Name, true)--(gunName, Equipping?)
CAS:BindAction("Reload", Reload, false, Enum.KeyCode.R)
end)
ReloadAnim:GetMarkerReachedSignal(“MagReloadStart”):Connect(function()
Mag.Transparency = 1
local prop = Mag:Clone()
prop.Transparency = 0
local children = prop:GetChildren()
for i = 1, #children do
children[i]:Destroy()
end
prop.CanCollide = true
prop.Parent = workspace
Debris:AddItem(prop)
end)
Depending on the scenario, I would disagree with you that putting events in functions shouldn’t be done. On that note, there is also the option of calling disconnect on an event that you no longer need.
local eventSignal = Instance.new("BindableEvent")
local function methodABTest()
local connection do
connection = eventSignal.Event:Connect(function ()
print("Hello, world")
end)
end
event:Fire()
connection:Disconnect()
end
I’m showing you an example of disconnecting an event. Moving the event connection out of the function does help for readability and depending on the way your code is structured, that may be the option you want to go for.
If you’re connecting functions to events inside a function call, then you also need to make sure to disconnect them when you don’t need them. In fact, this goes with any signal, regardless of where you connect it.
What you said is false. This is not a complicated example nor will functions stop working just because a event disconnection is called.