循环对未在Roblox中运行

huangapple go评论54阅读模式
英文:

Pairs loop not running roblox

问题

这是您提供的代码的翻译部分:

所以,我试图在Roblox中创建一个怪物。然而,出现了一些问题,但后来我进行了一些调试,意识到我在脚本中用来循环每个玩家的"pairs"没有运行。
以下是我的代码:

local dummy = script.Parent
local hrp = dummy.PrimaryPart
local sight = 30
local run = game:GetService("RunService")
local playerss = game:GetService("Players")
local players = playerss:GetChildren()
print("run")

run.Heartbeat:Connect(function()
    print("in loop")
        for _,player in pairs(players) do
	    local phrp = player.PrimaryPart
	    local dist = (hrp.Position - phrp.Position).Magnitude
	    print("on it")
	    if dist < sight then
		    print(phrp.Postion)
		    dummy.Humanoid.WalkToPoint = phrp.Position
		    dummy.Humanoid:MoveTo(phrp.Position)
	    end
    end
end)

请注意,我没有包含代码中的HTML实体引用,以确保代码在翻译后保持格式不变。

英文:

So, I was trying to make a monster in roblox. However there was something wrong but then I did some debugging and realized that the pairs I did to loop every single player in my script was not running.
Here's my code:

local dummy = script.Parent
local hrp = dummy.PrimaryPart
local sight = 30
local run = game:GetService(&quot;RunService&quot;)
local playerss = game:GetService(&quot;Players&quot;)
local players = playerss:GetChildren()
print(&quot;run&quot;)

run.Heartbeat:Connect(function()
    print(&quot;in loop&quot;)
        for _,player in pairs(players) do
	    local phrp = player.PrimaryPart
	    local dist = (hrp.Position - phrp.Position).Magnitude
	    print(&quot;on it&quot;)
	    if dist &lt; sight then
		    print(phrp.Postion)
		    dummy.Humanoid.WalkToPoint = phrp.Position
		    dummy.Humanoid:MoveTo(phrp.Position)
	    end
    end
end)

I tried looking for forums but NOTHING worked.

答案1

得分: 1

你有一个时间问题。脚本首先在怪物被加载到工作区时运行。因此,它获取所有服务,获取当前玩家列表,连接到心跳信号。

问题是,你从未获取更新的玩家列表。因此,它一直循环遍历在脚本首次运行时存在的玩家列表。而且很可能当脚本首次运行时存在的玩家数量为零。

要解决问题,将这行代码local players = playerss:GetChildren()移到心跳连接内部。

英文:

You have a timing issue. The Script first runs when the monster is first loaded into the Workspace. So, it grabs all the services, it grabs the list of the current players, it connects to the heartbeat signal.

The thing is, you never fetch an updated list of players. So it is looping over the list of players that were present when the Script first ran. And it's highly likely that the number of players that were present was zero.

So to fix your issue, move the line local players = playerss:GetChildren() inside the heartbeat connection.

huangapple
  • 本文由 发表于 2023年2月24日 14:53:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定