Hello, I want to make a function that kills the player when they touch a block, but for reasons i cant talk about i want to make it so when the player touches an object itll search for an object inside the part that the player touched and if it has a certain part the player will be killed. here is my code:
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
Player.onTouched:Connect(function(otherPart)
local humanoid = Player:FindFirstChildOfClass("Humanoid")
if humanoid then
if otherPart.Name == "killBrick" then
humanoid.Health = 0
end
end
end)
However, I get this error:
-- ServerScriptService.Script:4: attempt to index nil with 'onTouched'
If you want to check if specific part is touched you could do it like this. You could also use a loop to search for a specific part.
local Players = game:GetService("Players")
local killBrick = game.Workspace.killBrick
killBrick.Touched:Connect(function(hit)
local character = hit.Parent
if character then
local humanoid = character:FindFirstChildOfClass("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
end)
i put print statements at every if statement and conditions but when i put one under “if humanoid then” nothing would print out. It worked for the touched and character event though.
The reason this isn’t working seems to be because you are trying to see if the Player is touched, not the player’s character. Try using something such as:
or if the player will be stepping on something, reference the legs.
local function onPartTouched(otherPart)
local character = otherPart.Parent
if character:IsA("Model") and game.Players:GetPlayerFromCharacter(character) then
local humanoid = character:FindFirstChildOfClass("Humanoid")
if humanoid and humanoid.Health > 0 then
if otherPart.Parent:FindFirstChild("SpecificPartName") then
humanoid.Health = 0
end
end
end
end
local killPart = workspace:WaitForChild("KillBrick")
killPart.Touched:Connect(onPartTouched)
Try this in a regular server script inside of a part:
script.Parent.Touched:Connect(function(hit)
local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
if Player then
Player.Character:FindFirstChild("Humanoid").Health = 0
end
end)
That’s because you are trying to reference a character on someone’s PC, but from the server. The server can’t see things that is only on the player’s computer. Moving the script to StarterCharacterScripts would fix that issue. If it’s a server script, you can’t use
because the server doesn’t have it’s own player. You would have to specify who you are targeting using something such as checking when a player joins the game then checking if they touched something.
If you need me to explain it better, I will be happy to do so.