为什么总是出现这个错误,我试图在函数运行时让一个角色不可见

Why do keep getting this error, I'm trying to turn a character invisible when the function runs

local camera = workspace.CurrentCamera
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local startergui = game:GetService("StarterGui")
local char = Players.LocalPlayer.Character

local model = workspace.OceanVillagedr201["Wine Cellar"].WineDigitalkeypad
local screen = model.screen

local replicated_storage = game:GetService("ReplicatedStorage")
local CheckCode = Instance.new("RemoteEvent")
CheckCode.Name = "CheckWineCellarCodeEvent"
CheckCode.Parent = replicated_storage

local function Entercode(player)
    Players.LocalPlayer.Character.Humanoid.RootPart.Anchored = true
    for _,p in pairs(char:GetChildren()) do
         p.Transparency = 1
    end
    game.StarterGui = replicated_storage.EnterWineCellarCode
end
screen.ProximityPrompt.Triggered:Connect(function(player)
   Entercode()
end)

Im attempting to create a function that triggers when the proximity prompt is triggered, One piece of this Entercode() function is to toggle the playermodel's Transparency from 0 to 1 and Remove the Characters ability to move.

    local function Entercode(player)
    print("went")
    Players.LocalPlayer.Character.Humanoid.RootPart.Anchored = true
    for _,p in pairs(char:GetChildren()) do
         p.Transparency = 1
    end

But Im having trouble with this Piece. It keeps telling me "attempt to index nil" with anything dealing with trying to reference the Characters model. (FFC(), GetChildren(), Player.LocalPlayer.Character, etc.). I am using a local script because I plan to create a Remote Function for the result of EnterCode()

我认为你的问题是 在制作 char 是一个旧角色(玩家重生并制作了一个新角色)。一个快速的解决方法是在 Entercode:

中重新声明 char
local function Entercode()
    char = player.Character
    char.Humanoid.RootPart.Anchored = true
    for _, p in pairs(char:GetChildren()) do
        if p:IsA("BasePart") then
            p.Transparency = 1
        end
    end
    replicated_storage.EnterWineCellarCode.Parent = player.PlayerGui
end

还有一些其他错误,这里是我所做的一些更改:

local function Entercode()

在原始代码中,player 是一个参数,但没有作为参数发送幸好你在代码开头设置了播放器变量。

if p:IsA("BasePart") then
    p.Transparency = 1
end

在原始代码中,您没有检查 p 是否是一部分。

replicated_storage.EnterWineCellarCode.Parent = player.PlayerGui

在原始代码中,您尝试将 StarterGui 设置为 EnterWineCellarCode 我不知道您要做什么,但我假设你打算 父级 EnterWineCellarCodePlayerGui

最后,您可能想使用 GetDescendants() instead of GetChildren(). To better understand how the character works I recommend you read the wiki entry for it