RemoteEvents可以是两种方式吗?

时间:2020-05-23 13:09:49

标签: roblox

例如,这些脚本是否可以正常工作,挂起或给出错误消息?

(在脚本中)

RemoteEvent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

RemoteEvent:FireClient()
RemoteEvent.onServerEvent:Wait()
print("Hello World")

(在LocalScript中)

RemoteEvent = game:GetService("ReplicatedStorage"):WaitForChild("RemoteEvent")

RemoteEvent.onClientEvent:Wait()
RemoteEvent:FireServer()

2 个答案:

答案 0 :(得分:1)

为简单地回答您的问题,RemoteEvents可以双向工作。客户端到服务器和服务器到客户端都可以使用相同的事件。

您的示例可能会遇到一些计时问题。 服务器将启动,在所有零个客户端上启动,然后等待客户端将信号发送回去。 稍后,客户端将加入,然后等待服务器信号(已经发生)并陷入困境。

根据您希望的逻辑,当玩家加入游戏时,您可以等待执行代码:

-- server Script
local PlayerService = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage.RemoteEvent

PlayerService.PlayerAdded:Connect( function(player)
    -- Wait() will fire for any player that sends up the signal, so make sure that we know which player sent it
    -- instead, connect to the signal to make sure we're listening to the right player
    RemoteEvent.OnServerEvent:Connect( function(clientPlayer)
        if clientPlayer.Name == player.Name then

            print("Hello World", player.Name)

            -- pass some data from the server to the client
            RemoteEvent:FireClient( player, 1, 2, 3)
        end)
    end)
end)

然后在您的客户中...

-- LocalScript in PlayerScripts
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage.RemoteEvent

-- since there's no telling when this event will fire, tell the server that we've loaded!
RemoteEvent:FireServer()

-- wait for the server to respond and give us some data
local connection
connection = RemoteEvent.OnClientEvent:Connect( function(a, b, c)
    print("got data from server : ", a, b, c)

    -- disconnect so this event only fires once
    connection:Disconnect()
end)

答案 1 :(得分:0)

我想补充一下Kylaaa的回答,并回应您的代码示例,如果您的意图是等待客户端的响应,那么您还可以调用RemoteFunction而不是触发事件并等待事件来临回到你身边。像这样:

脚本:

game.Players.PlayerAdded:Connect(function(plr)
    local response = game.ReplicatedStorage.RemoteFunction:InvokeClient(plr, "Hello")
    print("Client said: " .. response)  
end)

LocalScript:

game.ReplicatedStorage.RemoteFunction.OnClientInvoke = function(text)
    print ("Server said: " .. text)
    return "Hi"
end

PS。 RemoteFunction也可以同时使用。