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

GUI Button upon click returns a nil upvalue, why?

Asked by 6 years ago

This script also works in a separate place, I'm just attempting to recreate the place for testing.

Upon the click of the button, an error that reads "attempted to index upvalue MyCharacter, which is a nil value" appears. The button has the localscript below and a brickcolor value. I think it's just a path error on my part or something, I'm not sure. Still newer to scripting. Thanks!

local MyCharacter = game.Players.LocalPlayer.Character
local x = script.Parent.PantColor.Value

script.Parent.MouseButton1Down:connect(function()
    MyCharacter["LowerTorso"].BrickColor = x
    MyCharacter["RightUpperLeg"].BrickColor = x
    MyCharacter["RightLowerLeg"].BrickColor = x
    MyCharacter["RightFoot"].BrickColor = x
    MyCharacter["LeftUpperLeg"].BrickColor = x
    MyCharacter["LeftLowerLeg"].BrickColor = x
    MyCharacter["LeftFoot"].BrickColor = x
end)

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

The Character doesn't exist yet
Patience is a virtue

The Character belonging to the player is likely not to exist at script init outside of a Studio test. You can fix this by waiting for the Character to exist

local MyPlayer = game.Players.LocalPlayer;
local MyCharacter = MyPlayer.Character or MyPlayer.CharacterAdded:wait()

This works by using short circuit evaluation, and waiting for the Character to exist if it doesn't exist yet.


In the event that it's in a place which won't reset when the character resets, you can keep the Character instance fresh by sticking this in alongside

MyPlayer.CharacterAdded:connect(function(c)
  MyCharacter = c
end)
0
Ah, thank you. I still don't understand why things work in Studio but not in the actual game itself. aquadrious 53 — 6y
Ad

Answer this question