This cannon script I made errors out if the player leaves while on a cannon. 13:48:00.115 - Workspace.Map.Cannon.CannonScript:19: attempt to index field 'Character' (a nil value)
local cannon = script.Parent local click = cannon.ClickDetector click.MouseClick:Connect(function(playerClick) if cannon.IsPlayerOn.Value == true then return end cannon.IsPlayerOn.Value = true local character = playerClick.Character or playerClick.CharacterAdded:Wait() local xrandom = math.random(-180,180) local yrandom = math.random(-45,0) cannon.MovingCannon.CannonPart:SetPrimaryPartCFrame(cannon.MovingCannon.CannonPart.PrimaryPart.CFrame * CFrame.Angles(math.rad(yrandom),0,0)) cannon.MovingCannon:SetPrimaryPartCFrame(cannon.MovingCannon.PrimaryPart.CFrame * CFrame.Angles(math.rad(xrandom),0,0)) if character then character.PrimaryPart.Anchored = true playerClick.Character:SetPrimaryPartCFrame((cannon.MovingCannon.CannonPart.CannonBarrel.CFrame + cannon.MovingCannon.CannonPart.CannonBarrel.CFrame.lookVector*4.5)) playerClick.Character:WaitForChild("Humanoid").WalkSpeed = 0 wait(2) if character then if character:FindFirstChild("HumanoidRootPart") then character.HumanoidRootPart.Anchored = false playerClick.Character:WaitForChild("Humanoid").Health = 0 local explosion = Instance.new("Explosion", game.Workspace) explosion.DestroyJointRadiusPercent = 0 explosion.BlastRadius = 0 explosion.Position = cannon.MovingCannon.CannonPart.CannonBarrel.Position + cannon.MovingCannon.CannonPart.CannonBarrel.CFrame.LookVector*4.5 cannon.Sound:Play() spawn(function() character.Humanoid.Health = 0 character.UpperTorso.Velocity = cannon.MovingCannon.CannonPart.CannonBarrel.CFrame.LookVector * 400 character.UpperTorso.RotVelocity = Vector3.new(math.random(-10,10),math.random(-10,10),math.random(-10,10)) end) wait(2) cannon.MovingCannon.CannonPart:SetPrimaryPartCFrame(cannon.MovingCannon.CannonPart.PrimaryPart.CFrame * CFrame.Angles(math.rad(-yrandom),0,0)) cannon.MovingCannon:SetPrimaryPartCFrame(cannon.MovingCannon.PrimaryPart.CFrame * CFrame.Angles(math.rad(-xrandom),0,0)) cannon.IsPlayerOn.Value = false end else print("No character detected.") cannon.MovingCannon.CannonPart:SetPrimaryPartCFrame(cannon.MovingCannon.CannonPart.PrimaryPart.CFrame * CFrame.Angles(math.rad(-yrandom),0,0)) cannon.MovingCannon:SetPrimaryPartCFrame(cannon.MovingCannon.PrimaryPart.CFrame * CFrame.Angles(math.rad(-xrandom),0,0)) cannon.IsPlayerOn.Value = false end end end)
How can I fix this?