通过远程函数传递模型

问题描述 投票:0回答:1

我在通过远程事件传递模型时遇到问题

模型(塔)最初存储在复制存储中,然后被克隆并移动到工作区中的文件夹中 (本地脚本)

tower = game.ReplicatedStorage.Towers.Boxer:Clone()
        
tower.Parent = workspace.Map.TowersToPlace

然后我通过远程事件传递它。

print(tower)    replicatedStorage.SpawnTowerEvent:FireServer(tower, mouse.Hit.Position)
end)

打印行正确打印塔,但服务器脚本出错,表示塔变量为零 (服务器脚本)

game.ReplicatedStorage.SpawnTowerEvent.OnServerEvent:Connect(function(plr, towerToPlace, pos)
    print(towerToPlace)
end)

-- 返回零

任何人都知道为什么尽管在本地脚本中正确定义了变量但没有被传递。

lua roblox
1个回答
0
投票

需要记住的是,在 LocalScripts 中创建的对象仅存在于客户端,而脚本在服务器上执行。

因此,当您使用 RemoteEvent 传递 Model 引用时,服务器不知道您在说什么,因为您正在引用一个在它眼中不存在的对象。根据文档有关 RemoteEvent 参数的限制:

非复制实例

如果 RemoteEvent 或 RemoteFunction 传递一个仅对发送者可见的值,Roblox 不会跨客户端-服务器边界复制它,并传递 nil 而不是该值。例如,如果脚本传递 ServerStorage 的后代,则侦听该事件的客户端将收到 nil 值,因为该对象不可复制给客户端。

因此,除非这是一个特定的设计决策,否则构建代码的更好方法是让服务器为您创建塔,而 LocalScript 只是告诉服务器要创建哪个塔以及在哪里。

所以在你的 LocalScript 中:

-- tell the server to create a tower
local tower = "Boxer"
game.ReplicatedStorage.SpawnTowerEvent:FireServer(tower, mouse.Hit.Position)

然后你的脚本找到客户端正在谈论的塔并创建它:

game.ReplicatedStorage.SpawnTowerEvent.OnServerEvent:Connect(function(plr, towerName, pos)
    local towerTemplate = game.ReplicatedStorage.Towers[towerName]
    if not towerToPlace then
        warn(string.format("Could not find a tower named %s", tostring(towerName))
        return
    end

    -- TO DO : make sure the player can create this kind of tower

    -- clone the tower into the workspace
    local towerToPlace = towerTemplate:Clone()
    towerToPlace:PivotTo(CFrame.new(pos))
    towerToPlace.Parent = workspace.Map.TowersToPlace
    print(towerName, " created at ", pos)
end)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.