Making a player auto-own items

What I am trying to do is to get a player to own only certain items, that I listed in the script. Issue is, this isn’t working. There are no errors, I am just confused why it isn’t working. If anyone can find a solution, would be helpful!

local players = game:GetService('Players')

players.PlayerAdded:Connect(function(player)
	local rt = player:FindFirstChild("Items")
	if rt then
		local st = rt:FindFirstChild("No hat")
		local rts = rt:FindFirstChild('Happy Time')
		local de = rt:FindFirstChild("Default")
		if st and rts and de then
			if st.Value == 'Unowned' then
			st.Value = 'owned'
			else
				end
			if rts.Value == 'Unowned' then
				rts.Value = 'owned' 
			else 
				end
				if de.Value == 'Unowned' then
					de.Value = 'owned' 
					else
				end
		end
	end
end)

Thanks!

It’s quite difficult to debug code when there are no clear errors. I would suggest these steps:

  • Before each if-statement, print the value that you’re checking. The script might fail at line 5 when it doesn’t find the “Items” folder, and won’t tell you about it.
  • Instead of FindFirstChild, use WaitForChild. It seems like you are adding these values to the player at some point (presumably in another PlayerAdded event), but if this code runs before that code the variables will all be nil.
  • Make sure you use the correct capitalization of '“Unowned” and “owned”. They are inconsistent in your code which might be accidental.
  • Just for the sake of writing readable code, three of your if-statements have an ‘else end’ that can be replaced with ‘end’ just fine because you’re not checking for anything else.
2 Likes

It is possible the ‘Items’ folder doesn’t exist. I would use a :WaitForChild() instead.

Yep, adding that, I’ll update you guys if it works.

WaitForChild worked.

local players = game:GetService('Players')

players.PlayerAdded:Connect(function(player)
	local rt = player:WaitForChild("Items")
	print(player.Name)
	if rt then
		local st = rt:WaitForChild("No hat")
		local rts = rt:WaitForChild('Happy Time')
		local de = rt:WaitForChild("Default")
		print(de.Value..","..rts.Value..","..st.Value)
		if st and rts and de then
			print(st.Value)
			if st.Value == 'Unowned' then
			st.Value = 'owned'
			else
			end
			print(rts.Value)
			if rts.Value == 'Unowned' then
				rts.Value = 'owned' 
			else 
			end
			print(de.Value)
				if de.Value == 'Unowned' then
					de.Value = 'owned' 
					else
				end
		end
	end
end)

Thanks.