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

Why i am getting "attempt to index upvalue 'Char' (a nil value)" Error at the 19th line?

Im trying to create a wood gathering script but i get the error that i mentioned at title. my code is here:

local Plr= game.Players.LocalPlayer
local Char = Plr.Character
local Mouse = Plr:GetMouse()

local GetWood = true

function ShowProgress(tree)
	if tree == 'Tree' then
		for i = 0,1, .01 do
			WG.BG.Bar.Progress.Size = UDim2.new(i,0,1,0)
			wait()
		end
	end
end

Mouse.Button1Down:connect(function()
	if Mouse.Target ~= nil and Mouse.Target.Parent.Name == 'Tree' and  GetWood == true then
		local Wood = Mouse.Target
		if (Wood.Position - Char.HumanoidRootPart.Position).magnitude <10 then
			GetWood = false
			WG = Plr.PlayerGui.WoodGathering
			WG.BG.Visible = true
			Char.Humanoid.WalkSpeed = 0
			for i, v in pairs(Wood.Parent.Leaves:GetChildren())do
				if v:IsA('Part') then
					v.Anchored = false
				end
			end
			Wood:Destroy()
			--Drop Wood
			WG.BG.Visible = false
			GetWood = true
		end
	end
end)

2 comments

0

if Char then

0

Since my fix worked, could you accept it?

1 answer

This is because scripts will execute faster than ROBLOX can load the assets of the game. You'll have to compensate for this in most future programs you'll end up writing.

It is also suggested that you define the Character within the Button1Down RBXScriptSignal since it'll redefine the Character every time. Why is this important? Well, this is because when the Character resets, it is replaced; therefore the previously declared Character will no longer be referencing the new Character, meaning it'll give poor data, or throw an error entirely... So to solve this issue, we will ask to get the Character every time the event runs to essentially refresh it.

So, to do this we'll need to compensate for the Character (wait for it) as said above. To do so, we can use the :Wait() method of Character's CharacterAdded RBXScriptSignal—this will call when a Character is added (respawned)—to ask the script to yield until the Character is confirmed and allocated:

local Player = game:GetService("Players").LocalPlayer
local Cursor = Player:GetMouse()

Cursor.Button1Down:Connect(function()
	local Char = Player.Character or Player.CharacterAdded:Wait()
	print(Char.Name)
end)

1 comment

0

Thank you so much it worked! I am new at lua and scriptig but i'll remember it next time! Cheers

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