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?
01 | function onClicked(player) |
02 | if player.Character:FindFirstChild( "Humanoid" ) ~ = nil and player.Character:FindFirstChild( "Helmet" ) = = nil then |
03 | local g = script.Parent.Parent.Helm:clone() |
04 | g.Parent = player.Character |
05 | local C = g:GetChildren() |
06 | for i = 1 , #C do |
07 | if C [ i ] .className = = "Part" or "Union" then |
08 | local W = Instance.new( "Weld" ) |
09 | W.Part 0 = g.Middle |
10 | W.Part 1 = C [ i ] |
11 | local CJ = CFrame.new(g.Middle.Position) |
12 | local C 0 = g.Middle.CFrame:inverse()*CJ |
13 | local C 1 = C [ i ] .CFrame:inverse()*CJ |
14 | W.C 0 = C 0 |
15 | W.C 1 = C 1 |
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.
1 | if C [ i ] .className = = "Part" or "Union" then |
Let's break the code into pieces.
1 | if | C [ i ] .className = = "Part" | or | "Union" | then |
2 |
3 | if |
4 | C [ i ] .className = = "Part" |
5 | or |
6 | "Union" |
7 | then |
The 4th part of this code will create an error, because you're basically saying to the computer...
1 | if "Union" then |
2 | -- It's basically saying... |
3 | if true then |
4 | -- Because "if" statements determine whether the condition is true or not |
5 | -- Now let's look at a line of your code |
6 | W.Part 1 = C [ i ] -- Line 10 |
7 | -- 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. |
8 |
9 | -- 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.
1 | if C [ i ] .ClassName = = "Part" or C [ i ] .ClassName = = "UnionOperation" then |
2 | -- "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".
1 | if C [ i ] :IsA( "BasePart" ) then |
1 | -- Delete line 25 |
2 | for i = 1 , #C do |
3 | if C [ i ] :IsA( "BasePart" ) then |
4 | C [ i ] .Anchored = false |
5 | C [ i ] .CanCollide = false |
6 | end |
7 | end |