How can i not unequip a tool but you can only switch tools? I can't really wrap my head around it. I didn't do the code when you switch tools. I only tested it for one tool but when i unequip the tool it lags then freezes. This is the error: ? Something unexpectedly tried to set the parent of FastCastGun to ProGamer(Character) while trying to set the parent of FastCastGun. Current parent is Backpack. (x2). This error keep repeating simultaneously with the lag. How can I fix it and how to make the script when you can only switch tools? This applies in many fps games.
Heres my code:
local animateequip = script.Parent.animationequip local anim = script.Parent.Animation local equipped = false animateequip.OnServerEvent:Connect(function(player) equipped = true if equipped == true then local hum = player.Character.Humanoid local equip = hum:LoadAnimation(anim) equip:Play() -- is it the animation? end end) local function characteradded(character) local hum = character.Humanoid print(character) hum:EquipTool(script.Parent) script.Parent.Unequipped:Connect(function()-- this one maybe equipped = false if equipped == false then equipped = true hum:EquipTool(script.Parent) end end) end local function playeradded(player) player.CharacterAdded:Connect(characteradded) local charact = player.Character if charact then characteradded(charact) end end game.Players.PlayerAdded:Connect(playeradded) for i,v in pairs(game.Players:GetPlayers()) do playeradded(v) end
This happens because as soon as you unequip the tool, it becomes the child of your Backpack. So the game gets confused since at that moment you're setting the tool to your character while it's setting the parent to the Backpack.
local RunService = game:GetService("RunService") local client = game.Players.LocalPlayer local char = client.Character or client.CharacterAdded:Wait() local backpack = client.Backpack script.Parent.Unequipped:Connect(function() local tool = backpack.ChildAdded:Wait() if script.Parent == tool then RunService.Heartbeat:Wait() char.Humanoid:EquipTool(script.Parent) print("Re-equippingTool") else print("SwitchingTool") end end) -----EXPLANATION----- --[[ First, I retrieved RunService, got the client, waited for the character to be added, and got the backpack.(You probably don't need to wait for the char to be added) Next, I detect if the tool gets unequipped. If it does get unequipped then, it looks at the child that was added to the backpack and detects if it's the tool. If it is the tool then it waits for a moment then re-equips the tool otherwise, if the client is switching tools it will do nothing. ]]
You can find a way to put this in your code.
I saw that you used pairs
on an array.
Use ipairs
for arrays.
Use pairs
for dictionaries.
The i
in ipairs
means Index.