使用RemoteEvent通信
客户端到服务器
在ReplicatedStorage下新建RemoteEvent,命名为RemoteEventTest
新建localscript脚本
脚本代码如下
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage:WaitForChild("RemoteEventTest")
-- 触发远程事件,传递数据参数
remoteEvent:FireServer(BrickColor.Red(), Vector3.new(0, 25, 0))
新建Script脚本
Script代码如下
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage:WaitForChild("RemoteEventTest")
-- 创建新的部件
local function onCreatePart(player, partColor, partPos)
print(player.Name .. " fired the remote event")
local newPart = Instance.new("Part")
newPart.BrickColor = partColor
newPart.Position = partPos
newPart.Parent = workspace
end
-- 当客户端触发远程事件时调用 "onCreatePart()"
remoteEvent.OnServerEvent:Connect(onCreatePart)
执行效果
服务器到客户端
使用原先的RemoteEventTest,Script,LocalScript。
Script代码修改为
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local remoteEvent = ReplicatedStorage:WaitForChild("RemoteEventTest")
local function onPlayerAdded(player)
-- 触发远程事件
remoteEvent:FireClient(player, Players.MaxPlayers, Players.RespawnTime)
end
Players.PlayerAdded:Connect(onPlayerAdded)
LocalScript代码修改为:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage:WaitForChild("RemoteEventTest")
-- 忽略传递的 player;从额外传递数据开始
local function onNotifyPlayer(maxPlayers, respawnTime)
print("Incoming server event...")
print(maxPlayers, respawnTime)
end
-- 当服务器触发远程事件时调用 "onNotifyPlayer()"
remoteEvent.OnClientEvent:Connect(onNotifyPlayer)
执行效果为
服务器给多个客户端传送数据时,每个客户端有相同的对应的接收函数即可,。
客户端给客户端发送数据时,通过服务器进行通信。