Need help with script, Getting "nil" value error

Hello. I am trying to create a load out / class system for my game, and this is my plan:

When a new player is added, a folder called “ClassFolder” is created in them, and inside that folder an integer value called “ClassValue” is created. Then, in a separate script, when the button for the class they selected is pressed, we go ahead and change the value of ClassValue so we can later retrieve it in an if else if array determining which weapons to give the player.

So far here is my code:

Initial script to put the load out GUI into the player’s gui screen.

game.Players.PlayerAdded:Connect(function(plr)
	local CloneMe = game.ServerStorage.ClassLoadout:Clone()
	CloneMe.Parent = plr.PlayerGui
end)

Local Script placed in one of the GUI buttons that selects a class to preview.

game.Players.PlayerAdded:Connect(function(plr)
	local Class = plr.ClassFolder.ClassValue
	
	
end)

script.Parent.MouseButton1Click:Connect(function()
	local Name = script.Parent.Parent.Parent.ClassNameS
	local Wep = script.Parent.Parent.Parent.ClassWeapons
	local Desc = script.Parent.Parent.Parent.ClassDesc
	local Info = game.ReplicatedStorage.Classes.Description:FindFirstChild(script.Parent.Name)
	
	Name.Text = script.Parent.Name
	Wep.Text = Info.ClassWeapons.Value
	Desc.Text = Info.ClassDesc.Value
	
	script.Parent.Parent.Parent.Loadout.Value = script.Parent.Name

    Class.Value = 1

end)

(The code that really matters is the first function and the last line)

In theory, I believe that when the button is clicked, the value in the player’s ClassFolder called ClassValue should be changed to 1, from the initial 0. Instead, when this code is called, I receive the error message stating

[Players.migte1.PlayerGui.ClassLoadout.Frame.ScrollingFrame.Army.LocalScript:23: attempt to index nil with ‘Value’]

I don’t understand what I am doing wrong and I would highly appreciate it if anyone knew a solution or/and what I was doing wrong.

Thanks,
migte

local Class makes it so the Class variable is only in the PlayerAdded function. You need to define Class outside of the function, at the top of the script

1 Like

You mean to make the variable global, correct?

Two main issues which I can see within your LocalScript:

PlayerAdded would be fired for every Player who joins after this Player since LocalScripts always run after the Player, who this LocalScript is running for, has joined.

This is localised to the function’s scope, so you can’t access it from the global/other scopes.

I recommend using the LocalPlayer and defining it in the global scope:

local Class = game:GetService("Players").LocalPlayer:WaitForChild("ClassFolder").ClassValue;
--// GetService is the most canonical way to get services
1 Like

That worked, Thanks!

I removed the Player Added function, and defined “class” with the Get Service code you provided, and it worked just fine. Thank you for all the help!

1 Like