# イベントとConnect：「〜したとき」に動かす

> ロブロックス（Roblox）のスクリプトは、「ふれたとき（Touched）」「プレイヤーが参加したとき（PlayerAdded）」などのイベントに、Connectで関数をつなぐことで動きます。

- URL：https://roblox.minecraft-okinawa.com/basics/events-and-connect/
- 更新日：2026-11-13

## 基本の形

```text
イベント:Connect(function(引数)
	-- イベントが起きたときにしたいこと
end)
```

## よく使うイベント

| イベント | いつ起きる？ |
|---|---|
| [BasePart.Touched](https://roblox.minecraft-okinawa.com/reference/classes/BasePart/) | パーツに何かがふれたとき |
| [Players.PlayerAdded](https://roblox.minecraft-okinawa.com/reference/classes/Players/) | プレイヤーが参加したとき |
| [Player.CharacterAdded](https://roblox.minecraft-okinawa.com/reference/classes/Player/) | キャラクターが出現したとき |
| [ClickDetector.MouseClick](https://roblox.minecraft-okinawa.com/reference/classes/ClickDetector/) | パーツがクリックされたとき |
| [ProximityPrompt.Triggered](https://roblox.minecraft-okinawa.com/reference/classes/ProximityPrompt/) | 近くでボタンを押したとき |
| [RunService.Heartbeat](https://roblox.minecraft-okinawa.com/reference/classes/RunService/) | 毎フレーム |

## Touchedは何度も起きる

足がパーツにふれると、Touchedは短い時間に何度も起きます。1回だけ反応させたいときは、「デバウンス」という仕組み（処理中かどうかを覚えておく変数）を使います。

（Script／置く場所：パーツの中）

```lua
local part = script.Parent :: BasePart
local debounce = false

part.Touched:Connect(function(hit)
	if debounce then
		return
	end
	local character = hit.Parent
	if not character or not character:FindFirstChildWhichIsA("Humanoid") then
		return
	end
	debounce = true
	task.wait(0.5)
	part.Transparency = 1
	part.CanCollide = false
	task.wait(3)
	part.Transparency = 0
	part.CanCollide = true
	debounce = false
end)
```


## つなぎを切る

（Script／置く場所：パーツの中）

```lua
local part = script.Parent :: BasePart
local connection

connection = part.Touched:Connect(function(hit: BasePart)
	print(hit.Name .. " がふれた")
	connection:Disconnect()
end)
```


Connectの戻り値を変数に入れておくと、Disconnectでつなぎを切れます。1回だけ反応させたいときは、Onceを使う方法もあります。

執筆：鈴木孝昌（現役プロジェクトマネージャー／プログラミング講師）／運営：沖縄マイクラ部 プログラミングスクール「クロスウェーブ」（https://minecraft-okinawa.com/）