Roblox Lua 运行 按下按键时的脚本,并且您距离一定距离

Roblox Lua run script when key pressed and you are a certain distance away

我正在尝试在 Roblox 中制作一个脚本,这样如果您在 20 个螺柱之外并按下 E,它将弹出一个 NPC 对话框。它在 LocalScript 中 运行。目前我只是让它在您按 E 时显示一条消息,但是它不会显示该消息。

local HumanoidRootPart = game.Players.LocalPlayer:WaitForChild("HumanoidRootPart")
local UserInputService = game:GetService("UserInputService")
local part = game.workspace.TableBox.TableTop

UserInputService.InputBegan:connect(function(keyCode)
    if keyCode.keyCode == Enum.KeyCode.E then
        if (part.Position - HumanoidRootPart.Position).magnitude < 20 then
            print("E has been pressed")
        end
    end
end)

我在输出中也遇到了这个错误(橙色):

Infinite yield possible on 'Players.icrann:WaitForChild("HumanoidRootPart")'

我希望 local HumanoidRootPart = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart") 可以工作,但最终会出现错误:

Players.icrann.PlayerScripts.Script:1: attempt to index field 'Character' (a nil value)

而且当我玩游戏时,我在资源管理器中的角色看起来是这样的:

将其替换为 HumanoidRootPart。

local Player = game:GetService("Players").LocalPlayer
local character = Player.Character or Player.CharacterAdded:Wait()
local HumanoidRootPart = character:WaitForChild("HumanoidRootPart")

经过几个小时的研究,我找到了一种方法,虽然不是 100% 有效,但也差不多了。

local HumanoidRootPart = workspace.icrann:WaitForChild("HumanoidRootPart")
local UserInputService = game:GetService("UserInputService")
local part = workspace.TableBox.TableTop

UserInputService.InputBegan:connect(function(keyCode)
    print(HumanoidRootPart.Position)
    if keyCode.keyCode == Enum.KeyCode.E and (part.Position - HumanoidRootPart.Position).magnitude <= 20 then
        print("E has been pressed")
    end
end)

现在唯一的问题是获取玩家用户名。如果您对如何执行此操作有任何额外建议,请添加评论或答案。感谢所有试图提供帮助的人。

local HumanoidRootPart = game:GetService("Players").LocalPlayer:WaitForChild("HumanoidRootPart") --It is .LocalPlayer, cuz localplayer is the player on that client
local UserInputService = game:GetService("UserInputService")
local part = workspace.TableBox.TableTop

UserInputService.InputBegan:connect(function(keyCode)
    print(HumanoidRootPart.Position)
    if keyCode.keyCode == Enum.KeyCode.E and (part.Position - HumanoidRootPart.Position).magnitude <= 20 then
        print("E has been pressed")
    end
end)