I am trying to script a tool that when someone touches it, they get damaged and I also included if it detects if they are on the same team, then don’t damage them.
But there is an error that said: -- attempt to index nil with Character -- Line 12
Script:
local handle = script.Parent
local tool = handle.Parent
function IsTeamMate(Player1, Player2)
return (Player1 and Player2 and not Player1.Neutral and not Player2.Neutral and Player1.TeamColor == Player2.TeamColor)
end
handle.Touched:Connect(function(hit)
local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
local player = game.Players:GetPlayerFromCharacter(tool.Parent)
if hit.Parent.Name == tool.Parent.Name then return end
if IsTeamMate(player, Player) then print("isteammated") return end
Player.Character.Humanoid:TakeDamage(5)
end)
Line 12 is: Player.Character.Humanoid:TakeDamage(5)
local handle = script.Parent
local tool = handle.Parent
function IsTeamMate(Player1, Player2)
return (Player1 and Player2 and not Player1.Neutral and not Player2.Neutral and Player1.TeamColor == Player2.TeamColor)
end
handle.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid")then
local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
local player = game.Players:GetPlayerFromCharacter(tool.Parent)
if hit.Parent.Name == tool.Parent.Name then return end
if IsTeamMate(player, Player) then print("isteammated") return end
Player.Character.Humanoid:TakeDamage(5)
end
end)
This line here might return nil, if what it hits does not belong to a player character (such as a wall).
All you have to do is check to see if the variable is nil before trying to damage the players humanoid. I would also rewrite some of the lines so that the logic fits inside one if statement, as so:
handle.Touched:Connect(function(hit)
local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
local player = game.Players:GetPlayerFromCharacter(tool.Parent)
if hit.Parent.Name ~= tool.Parent.Name and not IsTeamMate(player, Player) and player then
Player.Character.Humanoid:TakeDamage(5)
end
end)
Hope this helps!
Edit:
If you don’t want to rewrite it into one if statement, then your code would look like this
handle.Touched:Connect(function(hit)
local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
local player = game.Players:GetPlayerFromCharacter(tool.Parent)
if hit.Parent.Name == tool.Parent.Name then return end
if IsTeamMate(player, Player) then print("isteammated") return end
if Player then Player.Character.Humanoid:TakeDamage(5) end
end)