Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Attempt to index nil with 'leaderstats' please help?

I've made a script for a collectible that gives you currency when you touch it. It works perfectly except it gives an error every time i enter the game/ test it in studio. (it gives me the error twice for 2 specific collectibles which i find weird)

Workspace.Worlds.World6.Ticket.TixScript:9: attempt to index nil with 'leaderstats'

The script:

db = false

function tixPickup(partTouching)
	if partTouching.Parent:FindFirstChild("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(partTouching.Parent)
		if db == false then
			db = true
			print("Tix Picked Up")
			player.leaderstats.Tix.Value = player.leaderstats.Tix.Value + 1
			script.Parent.Transparency = 1
			wait(10)
			script.Parent.Transparency = 0
			db = false
		end
		
		
	end
end

script.Parent.Touched:Connect(tixPickup)

I've used a yt tutorial for this but i can't remember which one

2 comments

0

Why are you setting db to true in the if statement only to set it to false at the end?

0

Its called debounce, its to prevent a function from being run while it is already running see this https://developer.roblox.com/en-us/articles/Debounce

2 answers

✓ Accepted answer

Use :WaitForChild() in order for script to wait on a child to load.

local Players = game:GetService("Players") or game:FindService("Players");
local Debounce = true;

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		if not Debounce then
			return
		end
		Debounce = false;
		local Char = hit.Parent
		local Player = Players:GetPlayerFromCharacter(Char);
		local leaderstats = Player:WaitForChild("leaderstats");
		local TixVal = leaderstats:WaitForChild("Tix");
		
		TixVal.Value = TixVal.Value + 1;

		script.Parent.Transparency = 1;
		wait(10)
		script.Parent.Transparency = 0;

		Debounce = true;
	end
end)

The error is saying that it's attempting to index something that doesn't exist with 'leaderstats', so:

  1. The part that fired the touched event does not have the child 'leaderstats'. This probably didn't happen because of the if statement.
  2. 'Tix' isn't parented under 'leaderstats'.
  3. 'Value' isn't a property of Tix.
  4. 'Value' is a child of Tix, and not a property. This probably isn't true.

1 comment

0

The answer is really simple, he is looking for a leaderstats instance without waiting it to load.

This discussion is preserved as it was. New answers, comments, and votes are closed.