Like the title says I have this CollectionService script, sometimes it works, sometimes it doesn’t work, and I think it’s because the object/objects the script is affecting, hasn’t been loaded in yet, how could I wait for the object to load in first before the script affects the object?
local CollectionService = game:GetService("CollectionService")
local function AddPartFunctionality(ammobox)
local Click = ammobox.ClickDetector
local function Enabler(Player)
--print("bngbdgh")
--==================================================
--Setting
--==================================================
local Ammo = math.huge --Amount of Ammo to give. Set it to "math.huge" to refill the gun's ammo.
local GunToRefillAmmo = {
"M9",
"M9-S",
"Ruger 22",
"Full-Auto Ruger 22",
"MAC-10",
"M1911",
--Add more gun here if you want
}
--==================================================
local Enabled = true
if Enabled and Player then
local AmmoRefilled = false
for _, GunName in pairs(GunToRefillAmmo) do
local Gun = Player.Backpack:FindFirstChild(GunName) or Player.Character:FindFirstChild(GunName)
if Gun then
local GunScript = Gun:FindFirstChild("GunScript_Server")
local Module = Gun:FindFirstChild("Setting")
if GunScript and Module then
local Module = require(Module)
if GunScript.Ammo.Value < Module.MaxAmmo and Module.LimitedAmmoEnabled then
Enabled = false
AmmoRefilled = true
local ChangedAmmo = (Ammo == math.huge or GunScript.Ammo.Value + Ammo >= Module.Ammo) and Module.MaxAmmo or (GunScript.Ammo.Value + Ammo)
GunScript.Ammo.Value = ChangedAmmo
GunScript.ChangeMagAndAmmo:FireClient(Player,Module.AmmoPerMag,ChangedAmmo,0)
end
end
end
end
if AmmoRefilled then ammobox:Destroy() end
end
end
Click.MouseClick:Connect(Enabler)
Click.MouseClick:Connect(function()
Enabler()
end)
--print("gvfdjkhfgjd")
task.wait(120)
ammobox:Destroy()
end
for i,v in pairs(CollectionService:GetTagged("LightAmmo")) do
AddPartFunctionality(v)
end
CollectionService:GetInstanceAddedSignal("LightAmmo"):Connect(function(object)
AddPartFunctionality(object):Wait(2)
end)