【问题标题】:Roblox Studio - how do I run a script right before game starts?Roblox Studio - 如何在游戏开始前运行脚本?
【发布时间】:2021-07-20 00:57:02
【问题描述】:

我正在尝试创建一个插件,在用户在 roblox studio 上玩游戏之前从服务器获取附加代码。

基本上,用户将使用类似 blockly 的东西在网站上创建 luau 代码,我想将该代码发送到 roblox studio。我见过一些插件不时从服务器获取新数据,我已经能够做到这一点,但我想看看是否有办法只在用户点击播放时获取新代码按钮,因为每 5 秒左右请求一次新数据可能会很昂贵。

下面是一个简单的插件,它会在游戏加载时尝试向服务器发送请求,但脚本永远不会超出game.Loaded:Wait()

主文件:

local Request = require(script.Parent.Request)
local URL = "http://localhost:3333"

local toolbar = plugin:CreateToolbar("Test")
local button = toolbar:CreateButton("Test", "Test", "rbxassetid://4458901886")

local isListening = false
local request = Request.new()
local ok
local json

local function onClick ()
    isListening = not isListening
    if (isListening == false) then      
        return print("Not listening")
    end
    print("Listening")
    if not game:IsLoaded() then
        print(game.Loaded)
        game.Loaded:Wait()
        print("Game has started")
        ok, json = request:Get(URL)
        print(ok, json)
    end
    
end

button.Click:Connect(onClick)

请求文件:

local Request = {}
Request.__index = Request

function Request.new()
    return setmetatable({}, Request)
end

function Request:Get(URL)
    local ok, result = pcall(game.HttpService.GetAsync, game.HttpService, URL)
    local json = game.HttpService:JSONDecode(result)
    return ok, json
end

return Request

【问题讨论】:

    标签: plugins lua roblox


    【解决方案1】:

    没有明确的信号来检测游戏何时开始。

    但是,只要您点击播放按钮,编辑会话就会结束,播放会话就会开始。当会话结束时,所有插件都被卸载。因此,您可以使用plugin.Unloading 信号来检测编辑会话何时结束,但它也会在用户关闭位置、停止播放测试或插件被禁用或卸载时触发。

    您可以将该信号与RunService:IsEdit() 函数结合使用,以便该行为仅在退出编辑模式时触发,但这仍然是一个非常模糊的信号。

    因此,在插件中的脚本中,您可以执行以下操作:

    local RunService = game:GetService("RunService")
    local Request = require(script.Parent.Request)
    local URL = "<YOUR URL>"
    
    -- listen for when sessions end
    plugin.Unloading:Connect(function()
        -- disregard sessions that aren't Edit Mode
        if not RunService:IsEdit() end
            return
        end
    
        print("Game about to start... maybe. The game might also be closing, or the plugin might be disabled from the PluginManager.")
        local ok, json = request:Get(URL)
        print(ok, json)
    end)
    

    调试此问题可能会很困难,因为在您启动 Play 会话时会清除输出控制台,因此您不会看到任何 print 语句。但是,如果您关闭该地点,您的日志将保留在欢迎屏幕上。只需转到查看 > 输出即可打开输出窗口。

    【讨论】:

    • 感谢您的回答!我会做一些测试并发布结果!
    • 好的,我不得不暂停这个项目,但是当我研究它时,我无法使用这个建议,插件卸载的代码似乎没有运行。现在我有时间再看看这个,所以我会测试更多
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 2011-05-16
    • 2020-11-08
    • 2019-11-08
    • 2020-10-17
    • 2020-03-12
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多