# 이벤트

## 개요

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

<figure><img src="https://2697870212-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhRPi87oM9ttlk5nyu7L7%2Fuploads%2Fgit-blob-55e006562c8b575b42ed92a7043d9176e3185a69%2FBind%20Event%20Diagram%20(1).png?alt=media" alt="" width="509"><figcaption></figcaption></figure>

## 이벤트에 함수 연결

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

```lua
local Part = script.Parent

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

## 이벤트에 연결된 함수 해제

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

```lua
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)
```

## 이벤트 발생 대기

Wait()을 사용하면 신호가 한 번 발생할 때까지 현재 스레드를 대기하고, 발생 시 전달된 인자들을 반환합니다. 아래는 반환값을 활용하거나 순차 대기로 이어지는 사용 예입니다.

플레이어 입장 시 해당 플레이어의 캐릭터가 준비될 때까지 대기한 뒤 Humanoid 초기화 (서버)

```lua
local Players = game:GetService("Players")

local function OnPlayerAdded(player)
    local character = player.Character or player.CharacterAdded:Wait()
    local humanoid = character:WaitForChild("Humanoid")
    humanoid.WalkSpeed = 16
end
Players.PlayerAdded:Connect(OnPlayerAdded)
```

Wait()가 넘겨주는 인스턴스로 후속 작업

```lua
local Folder = workspace:FindFirstChild("SpawnContainer")
local AddedChild = Folder.ChildAdded:Wait()
local Nested = AddedChild:FindFirstChild("Config")

if Nested and Nested:IsA("ModuleScript") then
    -- 모듈 로드 등 후속 처리
end
```

신호가 여러 값을 반환하는 경우: AncestryChanged는 (child, parent)를 넘김

```lua
local Part = workspace:FindFirstChild("MovingPart")
Part.Parent = nil
Part.Parent = workspace.TargetFolder

local Child, NewParent = Part.AncestryChanged:Wait()

if NewParent then
    print("New Parent: ", NewParent:GetFullName())
end
```

RemoteEvent로 서버에서 한 번만 내려줄 데이터를 받을 때까지 대기 후 처리 (클라이언트)

```lua
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvent = ReplicatedStorage:FindFirstChild("SessionReady")

if RemoteEvent then
    local sessionId, startTime = RemoteEvent.OnClientEvent:Wait()
    -- sessionId, startTime으로 UI 갱신 또는 게임 로직 진행
end
```

## 자주 쓰는 이벤트의 종류

### 충돌 이벤트

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

```lua
local Part = script.Parent

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

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

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

### 업데이트 이벤트

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

```lua
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)
```

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

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

```lua
local Players = game:GetService("Players")

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

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

```lua
local Players = game:GetService("Players")

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

### 캐릭터 스폰/사망 이벤트

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

```lua
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)
```

### 버튼 이벤트

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

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

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