이벤트

개요

이벤트는 게임 내에서 발생하는 다양한 상황(입장, 충돌 등)에 필요한 기능을 구현하기 위해 사용됩니다.

이벤트에 함수 연결

:Connect()를 사용하여 이벤트에 함수를 연결합니다.

local Part = script.Parent

local function OnTouched(otherPart)
  print("otherPart : ", otherPart.Name)
end
Part.Touched:Connect(OnTouched)

이벤트에 연결된 함수 해제

:Connect()로 이벤트를 연결할 때 반환되는 값을 변수에 할당하면, 이벤트가 필요하지 않을 때 해제할 수 있습니다.

local Part = script.Parent
local Connection = nil

local function OnTouched(otherPart)
    local partParent = otherPart.Parent
    local humanoid = partParent:FindFirstChild("Humanoid")
 
    if humanoid then
        if Connection ~= nil then
            Connection:Disconnect()	
        end
    end
end
Connection = Part.Touched:Connect(OnTouched)

자주 쓰는 이벤트의 종류

충돌 이벤트

이벤트가 연결된 오브젝트에 충돌한 오브젝트를 감지합니다. (예 : Kill Part에 닿은 캐릭터 감지)

local Part = script.Parent

local function OnTouched(otherPart)
  print("otherPart : ", otherPart.Name)
end
Part.Touched:Connect(OnTouched)

이벤트가 연결된 오브젝트의 영역(충돌 범위)에서 벗어난 오브젝트를 감지합니다. (예 : 함정 바닥에서 탈출)

local function OnTouchEnded(otherPart)
    print("TouchEnded : ", otherPart.Name)
end
part.TouchEnded:Connect(OnTouchEnded)

업데이트 이벤트

매프레임 마다 호출되는 이벤트입니다. (예 : 타이머 계산, 물체 이동, 물리 연산)

local RunService = game:GetService("RunService")
local Timer = 0

local function UpdateEvent(deltaTime)
    Timer = Timer + deltaTime
    
    if Timer >= 3 then
        Timer = 0
        print("Reset!)
    end
end
RunService.Heartbeat:Connect(UpdateEvent)

플레이어 입장/퇴장 이벤트

입장한 플레이어를 감지하는 이벤트입니다.

local Players = game:GetService("Players")

local function EnterPlayer(player)
    print("EnterPlayer : ", player.Name)
end
Players.PlayerAdded:Connect(EnterPlayer)

퇴장한 플레이어를 감지하는 이벤트입니다.

local Players = game:GetService("Players")

local function LeavePlayer(player)
    print("LeavePlayer : ", player.Name)
end
Players.PlayerRemoving:Connect(LeavePlayer) 

캐릭터 스폰/사망 이벤트

스폰된 캐릭터나 사망한 캐릭터를 감지하는 이벤트입니다.

local Players = game:GetService("Players")

local function EnterPlayer(player)
    -- Spawn
    local function SpawnCharacter(character)    
        local humanoid = character:WaitForChild("Humanoid")
        
        -- Die
        local function DeathCharacter()
            print(player.Name, "Die!")
        end
        humanoid.Died:Connect(DeathCharacter)
    end
    player.CharacterAdded:Connect(SpawnCharacter)
end
Players.PlayerAdded:Connect(EnterPlayer)

버튼 이벤트

버튼이 클릭되었을 때 실행되는 이벤트입니다.

local ScreenGui = script.Parent
local Button = ScreenGui.TextButton

local function OnActivated()
    print("Activated")
end
Button.Activated:Connect(OnActivated)

Last updated