Had this problem where I had to unanchor a motorcycle made up of different models, and it wouldn’t work. Just realized what I did wrong after writing all of this so I’m gonna share to the community how to solve it so members can look this up
Problem
The script is made to unanchor a model and its submodels upon TouchLeaving a seat, which for some reason is not working, I manually checked every part inside the model and everything is unanchored
Every time my character leaves contact with the motorcycle the TouchEnded function gets triggered 8 times or so. Also every part is marked as unanchored, when I use the toolbar to anchor and unanchor it back though it falls down normally
Code:
function unachorModel(model) --Unanchors a model
if model or (model:IsA("Model")) then --If the model is a model or is not nil
for _, part in ipairs(model:GetChildren()) do -- foreach part in models children do
if part:IsA("BasePart") then -- if the part is a part then unanchor it
part.Anchored = false
elseif part:IsA("Model") then -- if the part is a model then recurse this function
unachorModel(part)
end
end
else
return false -- make it known
end
return true -- process over
end
local seat = script.Parent
local mc = script.Parent.Parent
seat.TouchEnded:Connect(function(part)
local isHumanoid = part.Parent:FindFirstChild("Humanoid")
if isHumanoid then
print("Seat touched by a humanoid")
seat.NotifyPartName:FireAllClients(part.Name)
print(unachorModel(mc))
task. Wait(1)
end
end)
Solution:
The problem was that I was doing this in the Models, not wherever an instance had a children in the hierarchy. In my case I put a BasePart in an Union, the script was flagging only Models as something to unanchor the children of.
Practical explanation:
The error stands in these lines:if model or (model:IsA("Model")) then --If the model is a model or is not nil --LINE 2
and
elseif part:IsA("Model") then -- if the part is a model then recurse this function --LINE 6
To unanchor a Model, we need to unanchor all of its children and their children.
We’re checking for the children of the Models only. Instead, we should also check if the BaseParts of the Models have children. If they do and are BaseParts, then we should unanchor them too.
How is the code going to act?
Working function:
function unachorModel(inputPart) --Unanchors a model
local originalPartChildrenCount = #inputPart:GetChildren() -- number of the o.p.c.c.
if(inputPart and originalPartChildrenCount>0) then --if inputpart is truthy and its got children then
for i, children in pairs(inputPart:GetChildren()) do --for each children of the inputpart
if(children:IsA("BasePart"))then-- if the children is a basepart
children.Anchored = false --unanchor the thing
end
if(#children:GetChildren() > 0) then -- if this children has children then
unachorModel(children) -- treat it as a model and unanchor its children
end
end
end
end
Hope you understand this terrible topic, thanks for reading!
