Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

New "Bad cast" error, unsure of how to fix?

So. I have made a Morph which has a model, a script, parts and unions and a script that should add it to the player. But, I keep getting the error:

15:42:08.307 - bad cast
15:42:08.308 - Script 'Workspace.Model.Model.Spawn.Torso', Line 13 -- suitw.Part1 = G[i]
15:42:08.309 - Stack End

My code

function onTouch(hit)

    if hit.Parent:findFirstChild("Humanoid") ~= nil and hit.Parent:findFirstChild("BTorso") == nil then
        local suit = game.ServerStorage["BTorso"]:clone()
        suit.Parent = hit.Parent
        local G = suit:getChildren()
        for i=1, #G do
            if G[i].className == "Part" or "Unionoperation" or "Model" or "Script" then
                local suitW = Instance.new("Weld")
                suitW.Part0 = suit.MainPart
                suitW.Part1 = G[i]
                local autoW = CFrame.new(suit.MainPart.Position)
                suitW.C0 = suit.MainPart.CFrame:inverse()*autoW
                suitW.C1 = G[i].CFrame:inverse()*autoW
                suitW.Parent = suit.MainPart
            end
            local bpW = Instance.new("Weld")
            bpW.Part0 = hit.Parent["Torso"]
            bpW.Part1 = suit.MainPart
            bpW.C0 = CFrame.new(0, 0, 0)
            bpW.Parent = suit.MainPart
        end
        local c = suit:getChildren()
        for i=1, #c do
            c[i].Anchored = false
            c[i].CanCollide = false
        end
    end
end

script.Parent.Touched:connect(onTouch)

I have adapted my code from the answer on: https://scriptinghelpers.org/questions/28266/bad-cast-error

1 answer

✓ Accepted answer

Your problem is on line 8:

if G[i].className == "Part" or "Unionoperation" or "Model" or "Script" then

This always evaluates to true, because the latter three strings are all truthy, and thus all pass the if statement.

Also, checking the className is bad practice.

What you want to do is use IsA to check if the part inherits 'BasePart', like so:

if G[i]:IsA("BasePart") then

This discussion is preserved as it was. New answers, comments, and votes are closed.