I've been making a infection tool that if Q is pressed and the player's head hits the other player, it will remove all of their tools and give them the infection tool. My issue is that I tried seeing if the tool in the player's inventory is equal to "nil". But every time I try to use it, it says that the tool is not a valid member of Backpack. How do I solve this?
local hum = game.Players:GetPlayerFromCharacter(hit.Parent) if hum and hum.Backpack["infection tool"] == nil then local c = hum.Backpack:GetChildren() for i = 1, #c do c[i]:Remove() end wait(0.1) game.ServerStorage["infection tool"]:Clone().Parent = hum.Backpack end
This isn't the entire script, but it is the majority of it. It clones perfectly to the player's head for it to work, but the script above is the only code it has right now.
Backpack isn't an array, it's an instance. So instead of doing
if hum.Backpack["infected tool"] == nil then
do
if hum.Backpack:FindFirstChild("infected tool") == nil then
EDIT: My mistake, you can use either the bottom or top, but the top one will cause an error if it doesn't find anything.
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent) local Tool = Player.Backpack:FindFirstChild("infection tool") or Player.Character:FindFirstChild("infection tool") if Player and not Tool then Player.Backpack:ClearAllChildren() wait(.1) game.ServerStorage["infection tool"]:Clone().Parent = Player.Backpack end
The code above should work now.
What I've changed is I've added a variable called Tool, and it'll try to find the tool in the Backpack and Character, if it exists then Tool will be the Infect Tool, if it cannot find the Infect Tool then it'll be equal to nil.
I've also changed your :Destroy() code to Player.Backpack:ClearAllChildren()
This line of code accomplishes the same as yours but in a quicker and neater way.
I've also changed hum to Player as you're referencing the Player and not the Humanoid of the Players Character.
Also, when you equip a Tool it goes into your Character. You'll want to check the Character to see if the Tool you're removing from the Backpack also exists there, if it does then you'll want to :Destroy it. I didn't add that code as I do not know the name of the Tool.