All players get teleported, instead of one

So i have created this script that when a player uses the proxprompt he gets teleported into the cannon and gets shot.

My problem is that when 1 player uses it, all the other players in the game will also be teleported into the cannon. How am i able to fix this?

local cannon = script.Parent.ProximityPrompt
local touched = false
local Players = game:GetService("Players")
local Sound = script.Parent.CannonSound

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(Character)
	 print(Character.Name)
      cannon.Triggered:Connect(function(Triggered)
			
		Character.HumanoidRootPart.CFrame = script.Parent.Parent.Tele.CFrame
			touched = true
			cannon.Enabled = false
		wait(0.5)
		local bodyVelocity = Instance.new("BodyVelocity")
		
		bodyVelocity.Velocity = Vector3.new(0,200,150)
		bodyVelocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
		bodyVelocity.P = math.huge
		
		bodyVelocity.Parent = Character.HumanoidRootPart
		
		Sound:Play()
		task.wait(1)
		touched = false
			bodyVelocity:Destroy()		
			task.wait(5)
			cannon.Enabled = true
	    end)
    end)
end) 

Heres the code ^^

The reason why that is happening is because you are creating the “cannon.Triggered” event for every player that joins which causes the code to run for all the players. To fix this, you can have one event that handles the “cannon.Triggered” event and get the player who triggered it from the “Triggered” argument:

local cannon = script.Parent.ProximityPrompt
local touched = false
local Players = game:GetService("Players")
local Sound = script.Parent.CannonSound

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(Character)
	 print(Character.Name)
         --Do stuff you want to happen when a player's character is added
    end)
end) 


cannon.Triggered:Connect(function(Triggered)
	   local Character = Triggered.Character
       local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")         
       if not HumanoidRootPart then return end

		HumanoidRootPart.CFrame = script.Parent.Parent.Tele.CFrame
			touched = true
			cannon.Enabled = false
		wait(0.5)
		local bodyVelocity = Instance.new("BodyVelocity")
		
		bodyVelocity.Velocity = Vector3.new(0,200,150)
		bodyVelocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
		bodyVelocity.P = math.huge
		
		bodyVelocity.Parent = HumanoidRootPart
		
		Sound:Play()
		task.wait(1)
		touched = false
	        bodyVelocity:Destroy()		
		task.wait(5)
		cannon.Enabled = true
end)

1 Like