Why won't this script work?

Hi developers,

I was wondering why this script won’t work:

game.Players.LocalPlayer.CharacterAdded:Wait()

local inputService = game:GetService("UserInputService")
local localPlayer = game.Players.LocalPlayer
local humanoid = localPlayer.Character:WaitForChild("Humanoid")
local holdAnim = humanoid:LoadAnimation(script.Parent.Animation)
holdAnim.Looped = true
holdAnim.Priority = Enum.AnimationPriority.Action
local weapon = 1
humanoid:EquipTool(localPlayer.Backpack.Gun)
holdAnim:Play()
local changeWeapon = false

inputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.One then
		if not weapon == 1 then
			weapon = 1
			changeWeapon = true
		end
	elseif input.KeyCode == Enum.KeyCode.Two then
		if not weapon == 2 then
			print("Weapon doesn't equal 2")
			weapon = 2
			changeWeapon = true
		end
	end
	if changeWeapon == true then
		if weapon == 1 then
			humanoid:EquipTool(localPlayer.Backpack.Gun)
			holdAnim:Play()
		elseif weapon == 2 then
			humanoid:EquipTool(localPlayer.Backpack.Blocc)
			holdAnim:Stop()
		end
	end
	changeWeapon = false
end)

It doesn’t print anything and it says that weapon equals 1.
Idk why this is happening.

Here’s the explorer
image

I’ve had the issue where it actually does not 1 and ignores the rest which evaluates to false. Instead, use the not equal operator (~=):

inputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.One then
		if weapon ~= 1 then
			weapon = 1
			changeWeapon = true
		end
	elseif input.KeyCode == Enum.KeyCode.Two then
		if weapon ~= 2 then
			print("Weapon doesn't equal 2")
			weapon = 2
			changeWeapon = true
		end
	end
	if changeWeapon == true then
		if weapon == 1 then
			humanoid:EquipTool(localPlayer.Backpack.Gun)
			holdAnim:Play()
		elseif weapon == 2 then
			humanoid:EquipTool(localPlayer.Backpack.Blocc)
			holdAnim:Stop()
		end
	end
	changeWeapon = false
end)
1 Like