Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Can you check if a object is inside a certain folder?

Asked by
MattVSNNL 620 Moderation Voter
3 years ago

I made this ball that you can throw and I wanna code that if it touches something it will check if its an animal that touched it, Every animal will be inside an Animals folder, but I wrote a small code and it doesn't work, I researched for 30 minutes and got no result, I also have no errors, Can anyone help me?

Here's my code

local tool = script.Parent
local debris = game:GetService("Debris")
local cooldown = false
local cooldownTime = 5
local ballRemoveTime = 4
local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()

tool.Activated:Connect(function()
    if cooldown == false then
        cooldown = true
        local cloneBall = tool:FindFirstChild("Handle"):Clone()
        cloneBall.CanCollide = true
        cloneBall.Name = player.Name.."'s ball"
        cloneBall.Parent = workspace:FindFirstChild("ClonedBalls")

        local bodyVelocity = Instance.new("BodyVelocity")
        bodyVelocity.MaxForce = Vector3.new(5,0,0)
        bodyVelocity.Velocity = (char:FindFirstChild("HumanoidRootPart").Position) * 5
        bodyVelocity.Parent = cloneBall

        debris:AddItem(cloneBall, ballRemoveTime)

        cloneBall.Touched:Connect(function(hit)
            if hit.Parent:IsA("Part") or hit.Parent:IsA("MeshPart") then
                local folder = hit.Parent.Parent:FindFirstAncestorWhichIsA("Folder")

                if folder then
                    if folder:FindFirstChild(hit.Parent) then
                        print("Touched!")
                    end
                end

            end
        end)

        wait(cooldownTime)

        cooldown = false

    end

end)

1 answer

Log in to vote
0
Answered by 3 years ago

You can use Instance:FindFirstAncestor() and pass the name of the folder into the function to see if the instance is a child of the folder.

Ad

Answer this question