The error is on line 16. The error outputted is: 'attempt to index nil with 'Parent'' Even if I put it inside an if statement, it still brings an error, and I'm not sure why.
01 | local rs = game:GetService( "ReplicatedStorage" ) |
02 | local events = rs:WaitForChild( "Events" ) |
03 | local shootEvent = events:WaitForChild( "Shoot" ) |
04 |
05 | function newBullet(player,part,pos,damage) |
06 | if part.Parent:FindFirstChild( "Humanoid" ) ~ = nil then |
07 | local humanoid = part.Parent:FindFirstChild( "Humanoid" ) |
08 |
09 | if humanoid.Health > 0 then |
10 | humanoid:TakeDamage(damage) |
11 | end |
12 | else |
13 | local bullet = Instance.new( "Part" ,workspace:WaitForChild( "Ignore" )) |
14 | bullet.Anchored = true |
15 | bullet.CanCollide = false |
It may be because the player who is firing the remote event is not actually sending a part instance, so the 'part' parameter in your function is nil. Writing part.Parent
in such a case will error the script since it is telling the script to find a humanoid object in nil.Parent
.
But why wouldn't the part ever exist? Well, in the context of guns, it can happen if the player shoots at the sky.
So a simple fix would be to verify before anything else that a part instance was indeed sent.
01 | function newBullet(player,part,pos,damage) |
02 | if part ~ = nil then -- This is where we check if the part instance exists |
03 | if part.Parent:FindFirstChild( "Humanoid" ) ~ = nil then |
04 | local humanoid = part.Parent:FindFirstChild( "Humanoid" ) |
05 |
06 | if humanoid.Health > 0 then |
07 | humanoid:TakeDamage(damage) |
08 | end |
09 | else |
10 | local bullet = Instance.new( "Part" ,workspace:WaitForChild( "Ignore" )) |
11 | bullet.Anchored = true |
12 | bullet.CanCollide = false |
13 | bullet.BrickColor = BrickColor.new( "Black" ) |
14 | bullet.Position = pos |
15 | bullet.Size = Vector 3. new( 0.1 , 0.1 , 0.1 ) |
16 | game:GetService( "Debris" ):AddItem(bullet, 5 ) |
17 | end |
18 | end |
19 | end |
There is also an improvement I would make to the script on Line 6.
01 | function newBullet(player,part,pos,damage) |
02 | if part ~ = nil then |
03 | local humanoid = part.Parent:FindFirstChild( "Humanoid" ) -- This will return the humanoid instance if it exists, and if it doesn't then nil |
04 | if humanoid ~ = nil then |
05 | if humanoid.Health > 0 then |
06 | humanoid:TakeDamage(damage) |
07 | end |
08 | else |
09 | -- Humanoid not found; your code that creates a bullet goes here |
10 | end |
11 | end |
12 | else |