Attempt to index nil with 'UserId' on a gamepass

I’m trying to do the thing where it kills people who doesn’t have a gamepass but I failed, can someone help?

local MarketPlace = game:GetService("MarketplaceService")
local id = 35105690

script.Parent.Touched:Connect(function(Hit, Player)
	
	if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
		
		if not MarketPlace:UserOwnsGamePassAsync(Player.UserId, id) then
			
			print("This User didn't buy the gamepass")
			Hit.Parent.Humanoid.Health = 0
			
		else
			
			print("This User brought the gamepass")
			
		end
		
	end
	
end)

You dont need 2 parameters. You can get the player by one parameter.

Use the function GetPlayerFromCharacter to get the player who touched the brick.

1 Like
local MarketPlace = game:GetService("MarketplaceService")
local id = 35105690

script.Parent.Touched:Connect(function(Hit)
	
	if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
		
        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
		if not MarketPlace:UserOwnsGamePassAsync(Player.UserId, id) then
			print("This User didn't buy the gamepass")
			Hit.Parent.Humanoid.Health = 0
		else
			print("This User brought the gamepass")	
		end	
	end
end)
2 Likes

thank you so much!! I didn’t expect to someone reply this fast on a big website lol

No problems, lol, I always wait for a question

1 Like
local Players = game:GetService("Players")
local MarketPlace = game:GetService("MarketplaceService")
local GamePassId = 35105690

local Part = script.Parent

Part.Touched:Connect(function(HitPart)
	local HitModel = HitPart:FindFirstAncestorOfClass("Model")
	if not HitModel then return end
	local HitPlayer = Players:GetPlayerFromCharacter(HitModel)
	if not HitPlayer then return end
	
	local Success, Result = pcall(function()
		return MarketPlace:UserOwnsGamePassAsync(HitPlayer.UserId, GamePassId)
	end)
	
	if Success then
		if not Result then
			HitPlayer:LoadCharacter()
		end
	else
		warn(Result)
	end
end)

Just in case the issued MarketplaceService API request fails. You should also verify that it was a player’s character that touched the part, attempting to index nil with the field “UserId” would result in an error.

2 Likes

Thank you, so basically there’s always a chance for an event/function to fail, thus we need pcalls?

1 Like

For all API-based methods that issue requests to Roblox’s internal database, yes, such as UserOwnsGamePassAsync, UserHasBadge, GetGroupsAsync etc.

2 Likes