Simple check for gamepass script not working

I have no clue why, but sometimes this script works and sometimes it doesn’t.

local RS = game:GetService("ReplicatedStorage")
local sword = RS.Tools:WaitForChild("ClassicSword")
local players = game:GetService("Players")
local MS = game:GetService("MarketplaceService")

local productIDs = 
	{
		swordPass = "18246407"
	}

players.PlayerAdded:Connect(function(player)
	if MS:UserOwnsGamePassAsync(player.UserId, productIDs["swordPass"]) == true then
		wait(.1)
		local cloneSword = sword:Clone()
		cloneSword.Parent = player:WaitForChild("Backpack")
	end
end)

Sorry if this is a super basic question, still very new to scripting

Are you sure you enabled API service in your game security settings?

Try removing the strings of the gamepass ID to just

swordPass = 18246407

Yep, and again, it sometimes works and sometimes doesn’t but the thing is it never errors, so I’m not led to believe it’s an issue with something not loading, plus I’m also not given any infinite yields.

Tried this, still sometimes works, sometimes doesn’t.

And you own the gamepass, right?

It should be a number and you should add it into their character once it spawns.

local RS = game:GetService("ReplicatedStorage")
local sword = RS.Tools:WaitForChild("ClassicSword")
local players = game:GetService("Players")
local MS = game:GetService("MarketplaceService")

local productIDs = 
	{
		["swordPass"] = 18246407
	}

players.PlayerAdded:Connect(function(player)
	if MS:UserOwnsGamePassAsync(player.UserId, productIDs["swordPass"]) == true then
		repeat
			wait()
		until player.Character
		local cloneSword = sword:Clone()
		cloneSword.Parent = player:WaitForChild("Backpack")
	end
end)

Just gonna put this out there, you do not need the brackets and quotations. The same goes for indexing a table.

Alright, i didn’t know that, lol. Thank for that. I’ll just change it to what else I thought it could’ve been

Busy waiting here is unnecessary when there are events to detect when character adds .

Just do

local RS = game:GetService("ReplicatedStorage")
local sword = RS.Tools:WaitForChild("ClassicSword")
local players = game:GetService("Players")
local MS = game:GetService("MarketplaceService")

local productIDs = 
	{
		swordPass= 18246407
	}
players.PlayerAdded:Connect(function(player)
 player.CharacterAdded:Connect(function(Char)
  if MS:UserOwnsGamePassAsync(player.UserId, productIDs.swordPass) then
    local cloneSword = sword:Clone()
    cloneSword.Parent = player.Backpack
  end
 end)
end)

This worked, thank you, also just wondering would this work the same?

players.PlayerAdded:Connect(function(player)
 player.CharacterAdded:Wait()
 if MS:UserOwnsGamePassAsync(player.UserId, productIDs.swordPass) then
   local cloneSword = sword:Clone()
   cloneSword.Parent = player.Backpack
  end
end)

Yes that would work the same , i used the connect function to avoid unnecessary yielding.

1 Like