타이머와 이벤트

*이 콘텐츠는 AI(베타)를 사용해 번역되었으며, 오류가 있을 수 있습니다. 이 페이지를 영어로 보려면 여기를 클릭하세요.

라운드 진행 중에 스크립트는 시간을 추적하고 다른 스크립트 간에 신호를 전송해야 합니다.시간은 시간 스크립트를 사용하여 관리되며, 이벤트, Roblox 코딩의 개념은 일치종료와 같은 변경 사항을 신호할 것입니다.

이벤트로 신호 전송

이제 경기장에 플레이어가 있으므로 이벤트를 사용하여 경기 시작 신호와 타이머의 코드를 시작할 수 있습니다.나중에 이벤트를 사용하여 매치가 종료되었음을 신호하고 플레이어를 로비로 되돌리는 시간이 되었음을 신호할 수도 있습니다.

이 이벤트는 미리 빌드되지 않으므로 bindable events 라고 하는 사용자 지정 이벤트 개체를 만들어야 합니다.바인드 가능한 이벤트는 플레이어가 발동하는 작업에 자주 사용되며 Touched 또는 Changed와 유사합니다.

여러 스크립트가 동일한 바인더 이벤트를 수신할 수 있습니다.이렇게 하면 코드가 구조화되어 나중에 매치의 시작이나 끝에 대한 추가 코드를 더 쉽게 추가할 수 있습니다.

바인딩 가능한 이벤트 생성

일치시작과 끝에 바인딩할 수 있는 이벤트 개체를 만들어 시작하십시오.바인딩 가능한 이벤트는 클라이언트와 상호작용하지 않으므로 서버 스토리지에 저장할 수 있습니다.

  1. ServerStorage에서 이벤트라는 새 폴더를 만들고, 그 폴더에서 매치스타트와 매치엔드라는 두 개의 바인더 이벤트 를 만듭니다.

이벤트 사용

현재 플레이어가 아레나에 들어갈 때, 휴식은 타이머를 시작하는 대신 계속 재시작됩니다.주 게임 루프는 코드의 다음 부분으로 이동하기 전에 MatchEnd 이벤트가 발생할 때까지 중지하고 대기해야 합니다.

이벤트에는 기본 제공 함수 2개가 있습니다: Connect()Wait().이전처럼 Connect()을 사용하는 대신, MatchEnd에서 Wait()를 호출하여 게임 관리자 스크립트가 중지될 때까지 일시 중지합니다.이 경우 대기 함수는 게임 관리자가 매치가 종료되었다는 신호를 받을 때까지 코드를 일시 중지합니다.

  1. In 게임 관리자 , 폴더 Events 및 이벤트 MatchEnd 에 대한 변수를 생성합니다.


    -- 모듈 스크립트
    local moduleScripts = ServerStorage:WaitForChild("ModuleScripts")
    local matchManager = require(moduleScripts:WaitForChild("MatchManager"))
    local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
    -- 이벤트
    local events = ServerStorage:WaitForChild("Events")
    local matchEnd = events:WaitForChild("MatchEnd")
  2. 스크립트가 이동하기 전에 일치 종료 이벤트가 발생할 때까지 대기합니다. 루프 에서, 에, 입력: matchEnd.Event:Wait()


    while true do
    repeat
    task.wait(gameSettings.intermissionDuration)
    print("Restarting intermission")
    until #Players:GetPlayers() >= gameSettings.minimumPlayers
    print("Intermission over")
    task.wait(gameSettings.transitionTime)
    matchManager.prepareGame()
    -- 게임의 길이를 기다리는 자리 표시자.
    matchEnd.Event:Wait()
    end
  3. 테스트 게임.플레이어가 아레나에 있으면 휴식 루프 계속되지 않는지 확인하십시오.스크립트는 이제 matchEnd 신호가 발사될 때까지 대기 중입니다.

문제 해결 팁

이 시점에서 코드가 예상대로 작동하지 않으면 다음 중 하나를 시도하십시오.

  • matchEnd.Event:Wait()에서 점 또는 콜론 연산자의 사용을 두 번 확인하십시오.
  • MatchEnd가 바인드 가능한 이벤트이고 원격 이벤트와 같은 다른 입력아닌지 확인하십시오.

타이머 사용

경기가 끝나는 조건 중 하나는 스크립트를 통해 처리되는 타이머가 소진되는 것입니다.

타이머 설정

게임에 타이머를 추가하려면 아래 단계에서 미리 만든 모듈 스크립트를 사용하십시오.타이머를 시작하고 종료하는 함수와 남은 시간을 반환하는 함수를 포함합니다.

  1. 서버 저장소 > 모듈 스크립트에서 타이머라는 새로운 모듈 스크립트를 만듭니다.

    코드를 아래 코드로 바꿉니다.


    local Timer = {}
    Timer.__index = Timer
    function Timer.new()
    local self = setmetatable({}, Timer)
    self._finishedEvent = Instance.new("BindableEvent")
    self.finished = self._finishedEvent.Event
    self._running = false
    self._startTime = nil
    self._duration = nil
    return self
    end
    function Timer:start(duration)
    if not self._running then
    task.spawn(function()
    self._running = true
    self._duration = duration
    self._startTime = tick()
    while self._running and tick() - self._startTime < duration do
    task.wait()
    end
    local completed = self._running
    self._running = false
    self._startTime = nil
    self._duration = nil
    self._finishedEvent:Fire(completed)
    end)
    else
    warn("Warning: timer could not start again as it is already running.")
    end
    end
    function Timer:getTimeLeft()
    if self._running then
    local now = tick()
    local timeLeft = self._startTime + self._duration - now
    if timeLeft < 0 then
    timeLeft = 0
    end
    return timeLeft
    else
    warn("Warning: could not get remaining time, timer is not running.")
    end
    end
    function Timer:isRunning()
    return self._running
    end
    function Timer:stop()
    self._running = false
    end
    return Timer
  2. 매치매니저에서 GameSettings 및 타이머 모듈 필요.


    local MatchManager = {}
    -- 서비스
    local ServerStorage = game:GetService("ServerStorage")
    -- 모듈 스크립트
    local moduleScripts = ServerStorage:WaitForChild("ModuleScripts")
    local playerManager = require(moduleScripts:WaitForChild("PlayerManager"))
    local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
    local timer = require(moduleScripts:WaitForChild("Timer"))
  3. 변수 아래에서, myTimer와 같은 이름의 변수를 설정하여 새로운 타이머 개체를 만들고, timer.new()와 같습니다.이 개체는 타이머를 시작하고 중지하는 함수를 호출하는 데 사용됩니다.


    local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
    local timer = require(moduleScripts:WaitForChild("Timer"))
    -- 매치 시간을 추적하기 위해 사용할 새로운 타이머 개체를 생성합니다.
    local myTimer = timer.new()

시작과 중지

이제 타이머가 생성되었으므로 일치중에 포함된 함수 start()stop()를 사용하십시오.아래는 각 함수와 해당 함수가 받는 매개변수의 설명입니다.

  • start(time) - 타이머를 시작하고 초 단위의 시간을 매개 변수로 사용합니다.
  • finished:Connect(functionName) - 타이머가 완료되면 매개 변수로 전달된 함수를 실행합니다.
  1. In 매치 관리자 , 타이머가 완료될 때마다 실행할 새 함수 timeUp() 를 만듭니다. 테스트 인쇄 문을 포함하십시오.


    local myTimer = timer.new()
    -- 로컬 함수
    local function timeUp()
    print("Time is up!")
    end
    -- 모듈 기능
    function MatchManager.prepareGame()
    playerManager.sendPlayersToMatch()
    end
    return MatchManager
  2. 아래 timeUp() , 인쇄 문으로 명명된 함수 startTimer() 를 추가하십시오. 나중에 게임에서 타이머를 표시합니다.


    -- 로컬 함수
    local function timeUp()
    print("Time is up!")
    end
    local function startTimer()
    print("Timer started")
    end
  3. 타이머를 시작하고 중지하려면, in startTimer() :

    • 호출 myTimer.start() . 패스 gameSettings.matchDuration .
    • 호출 myTimer.finished:Connect() . 패스 timeUp() .

    -- 로컬 함수
    local function startTimer()
    print("Timer started")
    myTimer:start(gameSettings.matchDuration)
    myTimer.finished:Connect(timeUp)
    end

타이머 시작

타이머는 매치 시작 이벤트를 사용하여 매치 시작 시 트리거될 수 있습니다.

  1. 매치매니저에서 모듈 변수 아래에서 이벤트 폴더, 매치시작, 매치종료(미래의 수업에서 사용되는 항목)를 저장하는 변수를 만듭니다.


    -- 모듈 스크립트
    local moduleScripts = ServerStorage:WaitForChild("ModuleScripts")
    local playerManager = require(moduleScripts:WaitForChild("PlayerManager"))
    local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
    local timer = require(moduleScripts:WaitForChild("Timer"))
    -- 이벤트
    local events = ServerStorage:WaitForChild("Events")
    local matchStart = events:WaitForChild("MatchStart")
    local matchEnd = events:WaitForChild("MatchEnd")
    --타이머 생성
    local myTimer = timer.new()
  2. 위의 return MatchManager , 일치 시작 이벤트를 startTimer() 에 연결하십시오.


    -- 모듈 기능
    function MatchManager.prepareGame()
    playerManager.sendPlayersToMatch()
    end
    matchStart.Event:Connect(startTimer)
    return MatchManager
  3. 매치 시작 이벤트를 발사하려면 prepareGame()에서 matchStart:Fire()를 입력하십시오.


    -- 모듈 기능
    function MatchManager.prepareGame()
    playerManager.sendPlayersToMatch()
    matchStart:Fire()
    end
  4. 게임을 테스트합니다. 출력 창에서 타이머의 시작 및 중지 기능에 대한 인쇄 문을 볼 수 있는지 확인합니다.

완료된 스크립트

아래는 작업을 확인하기 위한 완료된 스크립트입니다.

MatchManager 스크립트


local MatchManager = {}
-- 서비스
local ServerStorage = game:GetService("ServerStorage")
-- 모듈 스크립트
local moduleScripts = ServerStorage:WaitForChild("ModuleScripts")
local playerManager = require(moduleScripts:WaitForChild("PlayerManager"))
local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
local timer = require(moduleScripts:WaitForChild("Timer"))
-- 이벤트
local events = ServerStorage:WaitForChild("Events")
local matchStart = events:WaitForChild("MatchStart")
local matchEnd = events:WaitForChild("MatchEnd")
-- 매치 시간을 추적하기 위해 사용할 새로운 타이머 개체를 생성합니다.
local myTimer = timer.new()
-- 로컬 함수
local function timeUp()
print("Time is up!")
end
local function startTimer()
print("Timer started")
myTimer:start(gameSettings.matchDuration)
myTimer.finished:Connect(timeUp)
end
-- 모듈 기능
function MatchManager.prepareGame()
playerManager.sendPlayersToMatch()
matchStart:Fire()
end
matchStart.Event:Connect(startTimer)
return MatchManager

게임 관리자 스크립트


-- 서비스
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")
-- 모듈 스크립트
local moduleScripts = ServerStorage:WaitForChild("ModuleScripts")
local matchManager = require(moduleScripts:WaitForChild("MatchManager"))
local gameSettings = require(moduleScripts:WaitForChild("GameSettings"))
-- 이벤트
local events = ServerStorage:WaitForChild("Events")
local matchEnd = events:WaitForChild("MatchEnd")
while true do
repeat
task.wait(gameSettings.intermissionDuration)
print("Restarting intermission")
until #Players:GetPlayers() >= gameSettings.minimumPlayers
print("Intermission over")
task.wait(gameSettings.transitionTime)
matchManager.prepareGame()
-- 게임의 길이를 기다리는 자리 표시자.
matchEnd.Event:Wait()
end