How can I stop this error from happening?

Hello developers, I am making a gamepass only area and I am checking to see if they own the gamepass, I have came across this error SOMETIMES, sometimes it errors, sometimes it works, here is my error!

“Workspace.MegaVIPRoom.Union.Script:12: attempt to index nil with ‘IsA’”

My code, and yes I know the gamepassId is set to xxxx

image

:GetPlayerFromCharacter function returns the Player from given Player.Character, in line 10, you’re indexing character.Parent, you don’t have to do .Parent, just keep it as :GetPlayerFromCharacter(character)

It’s probably something to do with the collision detection, since sometimes it detects the player, sometimes it doesn’t. Can you show me the part?

He’s using a touched function so the variable returned would be a limb, not the character model.

For example, the character variable could be LeftLeg or Head. That’s why you need to use .Parent

2 Likes

Basically just a box

image

Ah, I see it now, my bad. 33333

plr doesn’t exist, and it’s detecting a different part with no player (hence why plr does not exist). Instead, try verifying that character.Parent:FindFirstChild(“Humanoid”) is true, rather than checking if plr:IsA(“Player”) since GetPlayerFromCharacter always returns a player. (Note that the FindFirstChild method should be checked before getting the player from the character)

1 Like

Like this?

	local plr = game.Players:GetPlayerFromCharacter(character.Parent)
	local hum = character.Parent.Humanoid
	
	if character.Parent:FindFirstChild("Humanoid") then
		local plr = game.Players:GetPlayerFromCharacter(character.Parent)
		
		if MarketPlaceService:UserOwnsGamePassAsync(plr.UserId, gamepassId) then
			print("Owns the gamepass!")

		else
			print("Doesn't own the gamepass!")
			hum.Health = 0
		end

	end
	
	```

This works but it errors for the hats
1 Like

Do you mean that when a hat touches the part, it errors?

Yeah, I always get this

Humanoid is not a valid member of Accessory "Workspace.noahrepublic.DevAwardsBombastic

Then you probably need to write an exception where if it is an accessory, look for the Parent above the actual Parent (since the hats are structured like (Character > Accessory > MeshPart) where body parts are (Character > MeshPart))

This error happens because you’re assuming every instance that touches the parent is a player. You should have no errors if you include the check to make sure plr isn’t nil, which would be replacing line 12 with:
if plr then

1 Like

Do

if plr == nil then return end
-- If statement here

This is because sometimes the “character” is a random part, and not a player, so GetPlayerFromCharacter returns nil.