Search code examples
luarobloxluauroblox-studio

Why doesn't my Roblox Studio print script execute correctly


For some reason, my pretty short script just refuses to print out or do anything after declaring variables, does anyone have an answer? I think it may actually be the wait for child and wait() but I don't know, because I just started Lua. Code:

local player = game.Players.LocalPlayer
local character = player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local health = humanoid.Health
print(player)
print(character)
print(humanoid)

and another one, in which it does work but, I can't use the variable or functions declared:

local player = game.Players.LocalPlayer
UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(function(input, typing)
    if typing then return end
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        print(player, " pressed lmb")
    end
end)
local character = player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local debounce = false
local health = humanoid.Health

I already tried to alter, but it seems that the only variable that I can do print after is player, which is the first one, so I can't get the other ones information.


Solution

  • Depending on where your LocalScript is, you are likely going to run into a timing issue. If this is in StarterPlayer > StarterCharacterScripts, then the code won't execute until the player's character is already created. So the order of events will be this :

    1. Player joins the game
    2. Player's Character spawns in the world
    3. Your LocalScript starts to execute...
    • 1st line grabs the Local Player
    • 2nd line waits for the player's character to spawn....

    And here's where your problem hits, the character has already spawned, and this event won't trigger again until the player dies and respawns. So your code is stuck on line 2.

    Typically, scripts will check if the character exists first, and if it doesn't then it waits until the signal fires. So try something like this :

    local player = game.Players.LocalPlayer
    local character = player.Character
    if not character then
        character = player.CharacterAdded:Wait()
    end
    -- after this point, the player's character is guaranteed to exist