I made a hat that instead of having to touch the hat you have to click it, so i changed the script from an onTouch to an onClicked. But whenever i click on the hat i get the error "Bad Cast". Can anyone help me resolve this?
function onClicked(player) if player.Character:FindFirstChild("Humanoid") ~= nil and player.Character:FindFirstChild("Helmet") == nil then local g = script.Parent.Parent.Helm:clone() g.Parent = player.Character local C = g:GetChildren() for i=1, #C do if C[i].className == "Part" or "Union" then local W = Instance.new("Weld") W.Part0 = g.Middle W.Part1 = C[i] local CJ = CFrame.new(g.Middle.Position) local C0 = g.Middle.CFrame:inverse()*CJ local C1 = C[i].CFrame:inverse()*CJ W.C0 = C0 W.C1 = C1 W.Parent = g.Middle end local Y = Instance.new("Weld") Y.Part0 = player.Character.Head Y.Part1 = g.Middle Y.C0 = CFrame.new(0, 0, 0) Y.Parent = Y.Part0 end local h = g:GetChildren() for i = 1, # h do h[i].Anchored = false h[i].CanCollide = false end end end script.Parent.ClickDetector.MouseClick:connect(onClicked)
Tab your code correctly! It will look more organized.
"Bad cast" occurs when ROBLOX functions or object are given something that it is not expecting.
The error I see so far that will stop your script from working is on line 7.
if C[i].className == "Part" or "Union" then
Let's break the code into pieces.
if | C[i].className == "Part" | or | "Union" | then if C[i].className == "Part" or "Union" then
The 4th part of this code will create an error, because you're basically saying to the computer...
if "Union" then -- It's basically saying... if true then -- Because "if" statements determine whether the condition is true or not -- Now let's look at a line of your code W.Part1 = C[i] -- Line 10 -- At this point, the weld's Part1 is set to the object that the "for" loop is indexing. Unfortunately, if the object is not a BasePart, then it will throw that "bad cast" error. -- In short, that "bad cast" error happened due to the weld's Part1 set to something that it is not expecting (a "Part" object, for example)
So, if you want to include "UnionOperation" and "Part" objects as the welded parts, see if C[i]
is equal to each of the strings.
if C[i].ClassName == "Part" or C[i].ClassName == "UnionOperation" then -- "UnionOperation" is the actual term for Union objects
To type less for convenience, use the :IsA() method, and use "BasePart" as the argument, because it inherits both "Part" and "UnionOperation".
if C[i]:IsA("BasePart") then
-- Delete line 25 for i = 1, #C do if C[i]:IsA("BasePart") then C[i].Anchored = false C[i].CanCollide = false end end