roblox studio:ChildAdded 不起作用且没有输出?

存在一个问题:当我运行这个脚本时,它什么也不做并且没有输出,脚本放在文件夹中并检查同一文件夹。

script.Parent.ChildAdded:connect(function()
    print("开始块设置")
    local children = game.workspace["用户资产"].blocks:GetChildren()
    for i = 1, #children do
        if not children[i]:FindFirstChild("ClickDetector") and children[i].Name ~= "setup" then
            local cd = Instance.new("ClickDetector", children[i])
            cd.MaxActivationDistance = 10
        end
        if not children[i]:FindFirstChild("BreakDown") and children[i].Name ~= "setup" then
            local breac = script.BreakDown:Clone()
            breac.Parent = children[i]
            breac.BreakObject.Disabled = false
        end
    end
    print("块设置成功")
end)

添加部件到块文件夹的东西

local mouse = game.Players.LocalPlayer:GetMouse()
local debounce = false
mouse.KeyDown:Connect(function(key)
    if key == "z" then
        if debounce == false then
            debounce = true
            local part = Instance.new("Part",game.Workspace["用户资产"].blocks)
            part.Name = script.Parent.Parent.Name
            part.Size = Vector3.new(3,3,3)
            part.Anchored = true
            part.CFrame = CFrame.new(mouse.Hit.X,mouse.Hit.Y + 1.5, mouse.Hit.Z)
            part.Orientation = Vector3.new(0,0,0)
            wait(1)
            debounce = false
        end
    end
end)

原文链接 https://stackoverflow.com/questions/70558655

点赞
stackoverflow用户2860267
stackoverflow用户2860267

问题在于生成方块的代码位于一个 LocalScript 中。

在 LocalScript 中对世界所做的更改不会被复制到服务器或其他玩家。因此,由于您有一个在服务器端观察文件夹内容的 Script,它永远不会看到新添加的方块。如果您使用 Studio 的测试>客户端和服务器>启动本地服务器功能测试此代码,您会发现方块仅被创建在客户端上,而在服务器对世界的视图中,这些方块并不存在。

但是,这个问题的解决方案非常简单。您只需要将创建方块的逻辑移动到 Script 中。一种简单的方法是使用 RemoteEvents 从 LocalScript 通讯到 Script。

因此,请按照以下步骤进行:

首先,在 ReplicatedStorage 或其他地方创建一个 RemoteEvent,并为其命名为 CreateBlockEvent

接下来,在 Workspace 或 ServerScriptService 中创建一个 Script 来观察 RemoteEvent。

local createBlockEvent = game.ReplicatedStorage.CreateBlockEvent

createBlockEvent.OnServerEvent:Connect(function(player, name, cframe)
    -- 创建方块
    local part = Instance.new("Part", game.Workspace["users assets"].blocks)
    part.Name = name
    part.Size = Vector3.new(3,3,3)
    part.Anchored = true
    part.CFrame = cframe
    part.Orientation = Vector3.new(0,0,0)
end)

然后,更新您的 LocalScript 以触发 RemoteEvent,以便在服务器上创建方块。

local createBlockEvent = game.ReplicatedStorage.CreateBlockEvent

local mouse = game.Players.LocalPlayer:GetMouse()
local debounce = false
mouse.KeyDown:Connect(function(key)
    if key == "z" then
        if debounce == false then
            debounce = true
            -- 告诉服务器在哪里创建方块
            local name = script.Parent.Parent.Name
            local cframe = CFrame.new(mouse.Hit.X,mouse.Hit.Y + 1.5, mouse.Hit.Z)
            createBlockEvent:FireServer(name, cframe)

            -- 冷却
            wait(1)
            debounce = false
        end
    end
end)
2022-01-02 19:32:33