Hi I have recently been trying to code a shield system for a game I’m working on it was suppose to work as a forcefield being created when you hold down Q by equipping a tool. When the tool is equipped by holding down Q it triggers a forcefield to be created and when its unequipped the forcefield is destroyed but for some reason it creates 20+ forcefields and wont destroy any of them. I’ve tried putting in different if then statements as a precaution to stop it. But nothing works I think it has something to do with the RunService.Heartbeat
system but it could be something else.
Here’s my 2 local scripts in the tool
forcefield creation:
local shield = script.Parent
shield.Equipped:Connect(function()
print("works")
local player = shield.Parent
local force = Instance.new('ForceField')
force.Parent = player
end)
shield.Unequipped:Connect(function()
print("stopped")
local player = shield.Parent.Parent
local character = player.CharacterAdded:Wait()
local force = character:GetChildren("ForceField")
force:Destroy()
end)
equip tool script (which might be the problem)
local player = game.Players.LocalPlayer
local character = player.Character
local shield = script.Parent
if not character or not character.Parent then
character = player.CharacterAdded:Wait()
end
local humanoid = character:WaitForChild("Humanoid")
-- Vars: Input
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local desiredKey = Enum.KeyCode.Q
local function keyIsDown() -- Returns if the key is down or not
return UserInputService:IsKeyDown(desiredKey)
end
-- Vars: Tool
local tool = player.Backpack:WaitForChild("Shield")
local handle = tool.Handle
local isHeld = false;
-- Functions
local function equipTool()
if UserInputService:IsKeyDown(desiredKey) then
if isHeld == false then
humanoid:EquipTool(tool)
local player = shield.Parent
local force = Instance.new('ForceField')
force.Parent = player
else if isHeld == true then
return
end
end
else
humanoid:UnequipTools(tool)
local player = shield.Parent.Parent
local character = player.CharacterAdded:Wait()
local force = character:GetChildren("ForceField")
force:Destroy()
end
end
if not character:FindFirstChildWhichIsA('ForceField') then
if not UserInputService:IsKeyDown(desiredKey) then
RunService.Heartbeat:Connect(equipTool)
end
end