I am making an Easter egg hunt game, and I would like to be able to check if a player has touched a part (egg) that is a child of a model, without specifying the name of the part (egg).
A method I would use is for i, v in pairs(model)
.
just loop through each instance and check if the name/type/properties are the same. Which ever you want.
Or you could just say:
if v == easteregg then
This could be done easily.
for i,v in pairs(model:GetChildren()) do
if v:IsA('BasePart') then
v.Touched:Connect(function(part)
if part.Parent:FindFirstChild('Humanoid') then
print('Touched')
end
end
end
end
local players = game:GetService"Players"
local function onEggTouched(egg, hitPart)
local hitModel = hitPart:FindFirstAncestorOfClass"Model"
if hitModel then
local hitPlayer = players:GetPlayerFromCharacter(hitModel)
if hitPlayer then
--Do action with touching player.
end
end
end
for _, egg in ipairs(eggFolder:GetChildren()) do
if egg:IsA"Model" then
for _, part in ipairs(egg:GetChildren()) do
if part:IsA"BasePart" then
part.Touched:Connect(function(hitPart)
onEggTouched(egg, hitPart)
end)
end
end
end
end
Here’s a bit of pseudo-code which should help steer you in the right direction. The egg
parameter refers/points to the egg model that had one of its parts touched, hitPart
represents the touching part.
Why not keep it in one function?