Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago

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)
0
if Char then herrtt 387 — 4y
0
Since my fix worked, could you accept it? Ziffixture 6913 — 4y

1 answer

Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

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)
0
Thank you so much it worked! I am new at lua and scriptig but i'll remember it next time! Cheers emay0660 13 — 4y
Ad

Answer this question