So, I’ve made this server script that should check inside a player’s inventory and character if the player has any tool, but it keeps returning ServerScriptService.Server.Detector:16: attempt to index nil with 'Backpack'
For some reason, it seems the script even fails to find the character in the first place. Anyone knows how can I fix this?
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local folder = Workspace.Detector
for i, v in pairs(folder:GetChildren()) do
local colorpart = v.COLORPART
colorpart.Touched:Connect(function(part)
print(part)
local char = part
local player = Players:GetPlayerFromCharacter(char)
local backpack = player.Backpack
if not IsOn then
if char:FindFirstChild("IsWeapon") or backpack:FindFirstChild("IsWeapon") then
print("PLAYER HAS WEAPON")
end
else
return
end
end)
end
If the person that touched it is a character, usually part.Parent will give the character, Though this will still not work because if anything else touches it’ll error, so make sure to check if player isn’t nil before trying to get the backpack
Character models hold BaseParts inside of them. What you’re really looking for is part:FindFirstAncestorOfClass("Model")
This line will not always return a character object which could also be one of the reasons your script is erroring.
Fixed Code:
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local folder = Workspace.Detector
for i, v in pairs(folder:GetChildren()) do
local colorpart = v.COLORPART
colorpart.Touched:Connect(function(part)
print(part);
local char = part:FindFirstAncestorOfClass("Model");
local player = Players:GetPlayerFromCharacter(char);
if (not player) then return; end
local backpack = player.Backpack
if (not IsOn) then
if (char:FindFirstChild("IsWeapon", true)) or (backpack:FindFirstChild("IsWeapon", true)) then
print("PLAYER HAS WEAPON")
end
end
end)
end