Hi, this question is short but, I wanna know what’s the best way to get the character who touched a brick?
To elaborate, when a player touches a brick, it’s usually a part that is parented to the player’s character, but sometimes it is the child of a part that is parented to the player’s character, and I was wondering what’s the most reliable or easy way to get around this issue?
Here is how you would do it to get the character (Put inside the brick):
debounce = false
script.Parent.Touched:Connect(function(hit)
local human = script.Parent:FindFirstChild("Humanoid")
if human then
if debounce == false then
debounce = true
local character = human.Parent
wait(1)
debounce = false
end
end
end)
The way I would do it, is to detect whether or not the Touched Character has a humanoid in it, therefore meaning it is a players character, unless you have a game full of bots wondering around.
function touchedChar(hit) -- Creating a function
if hit.Parent:FindFirstChild("Humanoid") then -- Detects a humanoid inside the player's character
script.Parent.Transparency = 1 -- Making something happen when a part is touched
end
end
script.Parent.Touched:Connect(touchedChar)-- Calling the function
Use GetPlayerFromCharacter using the hit.Parent. So it won’t work on NPCs. And then you can use the character, because you know it’s a real player.
script.Parent.Touched:Connect (function(hit)
if(game.Players:GetPlayerFromCharacter(hit.Parent) or game.Players:GetPlayerFromCharacter(hit.Parent.Parent)) then
--Do stuff here.
end
end)
If you know it’s a player, then you know the hit is obviously the character, because it got it from there.
script.Parent.Touched:Connect(function(part)
if part.Parent:FindFirstChild("Humanoid") then
--what you wanna do
end
If you want to add debounce
debounce = false
script.Parent.Touched:Connect(function(part)
if part.Parent:FindFirstChild("Humanoid") and debounce == false then
-- whatever u want to do
debounce = true
wait(howlongyouwantdebouncefor)
debounce = false
end
All the above are good, but If you want to be extra.
local touched;
local cooldown = 4;
script.Parent.Touched:Connect(function( hit )
if hit:FindFirstAncestorWhichIsA("Model"):FindFirstChildOfClass("Humanoid") and not debounce then
touched = true;
wait(cooldown)
touched = false;
end;
end);
if you want to check if it a player in addition to that, you can use what @LightningLion58
local playersService = game:GetService("Players");
local touched;
local cooldown = 4;
script.Parent.Touched:Connect(function( hit )
local player = playersService:GetPlayerFromCharacter( hit:FindFirstAncestorWhichIsA("Model") );
if player and not debounce then
touched = true;
wait(cooldown);
touched = false;
end;
end);