I am making a script that charges up an orb for as long as your holding a key down. Everything was working fine except there was an error that I can't figure out.

Workspace.Moves.ChargingOrb:41: attempt to index global 'charging' (a nil value)

Main script

game.ReplicatedStorage.Moves.OnServerEvent:Connect(function(plr,mousehit,key,key2)
if key == "Orb" then
if key2 == "Start" then
local char = game.Players[plr.Name].Character
local hum = char.Humanoid
local root = char.HumanoidRootPart
charging = Instance.new("Part")
charging.Name = "Orb"
charging.Shape = Enum.PartType.Ball
charging.Material = Enum.Material.Neon
charging.Size = Vector3.new(0.2,0.2,0.2)
charging.BrickColor = BrickColor.new("Really red")
charging.CanCollide = false
charging.Parent = workspace

local weld = Instance.new("Weld")
	charging.CFrame = char.Head.CFrame * CFrame.new(0,0,-2)
	weld.Part0 = char.Head
	weld.Part1 = charging
	weld.C0 = char.Head.CFrame:Inverse()
	weld.C1 = charging.CFrame:Inverse()
	weld.Parent = charging

local function charge()
        local chargingPart = charging:Clone()
        chargingPart.Parent = charging
        chargingPart.Size = Vector3.new(0.1,0.1,0.1)
        chargingPart.CFrame = charging.CFrame * CFrame.new(math.random(-0.6,0.6),math.random(-0.6,0.6),math.random(-0.6,0.6))
        chargingPart.Anchored = true
        game.Debris:AddItem(chargingPart,0.01)
end

while true do
    spawn(charge)
    wait()
if charging == nil then
	break
end
end
elseif key2 == "End" then
	charging:Destroy()
end
end
end)

4 comments

0

maybe Charging gets destroyed

0

I thought about that, but I don't see where.

0

Destroy() sets the Parent property to nil, locks the Parent property, disconnects all connections and calls Destroy() on all children.

0

You already added it to Debris, but I don’t see where the GetService function was called