PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Chat Commands for In-Game Events

Chat Commands for In-Game Events

Jun 14 2019, 4:46 PM PST

Problem

You want to use the Chatted event so you can run code when you type something.

Solution

Use the Chatted event of Player.

local function onPlayerChatted(player, message)
	if message == 'removehead' and player.Character and player.Character:FindFirstChild("Head") then
		player.Character.Head:Destroy()
	end
end
local function onPlayerAdded(player)
	pl.Chatted:Connect(function (message) onPlayerChatted(player, message) end)
end
game.Players.PlayerAdded:Connect(onPlayerAdded)

Discussion

First, the onPlayerAdded function is connected to the Players/PlayerAdded|PlayerAdded event. Then, the onPlayerChatted function is connected to the Player/Chatted|Chatted event on newly-added Players. The chatted event sends only the message to the connected function, so we use an anonymous function to pass both player and message to onPlayerChatted. In that function, we check if the message is “removehead”, and also if the player’s head exists. Finally, we proceed to remove the speaker’s head!

Tags:
  • chat
  • command
  • coding