Roblox Studio - 如何在游戏启动之前运行脚本?

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

基本上,用户将使用类似于Blockly的工具在网站上创建Lua代码,我希望将该代码发送到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 == falsethen
        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)
    返回ok,json
end

return Request 
点赞
用户2860267
用户2860267

在游戏即将开始时没有明确的信号可以检测。

但是,每当你点击“播放”按钮时,编辑会话结束,播放会话开始。当一个会话结束时,所有插件都会被卸载。因此,你可以使用 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() then
        return
    end

    print("游戏即将开始...也可能游戏正在关闭,或者插件从 PluginManager 中被禁用。")
    local ok, json = request:Get(URL)
    print(ok, json)
end)

调试这个可能很困难,因为输出控制台在开始播放会话时会被清除,所以你不会看到任何 print 语句。但是,如果你关闭地图,你的日志将被保存在欢迎屏幕上。只需点击“查看”>“输出”来打开输出窗口即可。

2021-04-26 23:23:32