为什么我尝试从 roblox 上的不同脚本检索部件的 BrickColor.Name 时得到不同的值

Why do I get different values when trying to retrieve BrickColor.Name of a part from different scripts on roblox

我正在用 Roblox 写一个简单的游戏。

播放器中的一个脚本会更改播放器接触的所有灰色块的颜色。 部分中的其他脚本使其闪烁。这部分应该在被触摸时停止闪烁,然后它的颜色会发生变化。

当我触摸方块时,渲染颜色和玩家脚本中的颜色名称发生变化,但零件脚本中的颜色名称没有变化。 我添加了一些印刷品来帮助我弄清楚发生了什么。 我知道可以通过事件来解决它。但为什么会有不同的值?

此脚本在 StarterCharacterScripts 对象中:

print(":)")

local originalColor = BrickColor.new(0.639216, 0.635294, 0.647059)

local player = game.Players.LocalPlayer

local human = player.Character.Humanoid

print("Player logged:  " .. human.DisplayName)

human.Touched:Connect(function(hit,limb)
    if hit.BrickColor.Name == originalColor.Name then
        hit.Color = player.TeamColor.Color
    end
end)

while true do
        print("From human: " .. workspace.Test.BrickColor.Name)
        wait(3)
end

另一个脚本在对象中:

local greyPart=script.Parent
local myColor = greyPart.Color




print(greyPart.Name)
print(script.Parent.Name)

while myColor == script.Parent.Color do
    greyPart.Transparency = 1
    wait(1)
    greyPart.Transparency = 0
    wait(1)

    print("From part: " .. workspace.Test.BrickColor.Name)
end

触摸前得到的输出是这样的:

From human: Medium stone grey
From part: Medium stone grey (x2)

触摸之后是这样的:

  From human: Really red
  From part: Medium stone grey (x2)

出于安全原因,使用 LocalScript 对工作区进行更改只会将这些更改应用到拥有 LocalScript 的播放器。

如果您从 Studio 的“测试”选项卡玩游戏,并且 运行 有 3 名玩家和服务器,您可以看到实际效果。 我在 StarterCharacterScripts 中制作了一个简单的 LocalScript,将积木更改为随机颜色。这是它在所有不同的客户端和服务器上的样子:

服务器:

玩家 1 :

玩家 2 :

玩家 3 :

如果您希望将更改复制到所有玩家,则必须在脚本中进行。

I know it is possible to solve it with an event. But why the different values?

使用 RemoteEvent 是此问题的解决方案,因为您正试图从客户端影响服务器端更改。在 Roblox 客户端-服务器模型中,服务器是权威的,并且是唯一可以对游戏世界中的对象进行更改的服务器。当客户对您使用脚本的方式进行更改时,从本地客户的角度来看,该更改是可见的;但是,更改 不会 复制到其他玩家。这解释了您脚本的输出:在您的屏幕上,方块的 BrickColor 已经改变,但从另一个玩家的角度来看它仍然是灰色的。

A RemoteEvent 以及 RemoteFunction 可以从客户端发送信号,然后由服务器接收;这些信号可以告诉服务器对游戏世界进行更改,所有客户端都可以看到。在您的情况下,您的客户端脚本会检测玩家触摸的灰色部分,并将该信息通过 RemoteEvent 发送到服务器并告诉它更改该部分的 BrickColor.

RemoteEvent class 的 Roblox 参考页面说明如下:

A RemoteEvent is designed to provide a one-way message between the server and clients, allowing Scripts to call code in LocalScripts and vice-versa. This message can be directed from one client to the server, from the server to a particular client, or from the server to all clients.

在您的情况下,您会将一条消息从一个客户端定向到服务器,从 LocalScript.

调用服务器端 Script 中包含的函数

有关示例和更多详细信息,请参阅 RemoteEvent 参考页 here