A 플레이어 개체는 현재 연결된 클라이언트입니다.이 개체는 새 플레이어가 연결되면 Players 서비스에 추가되고, 결국 서버에서 연결이 끊어지면 제거됩니다.
Instance.Name 속성은 플레이어의 사용자 이름을 반영합니다.플레이어에 대한 정보를 저장할 때 플레이어가 자신의 사용자 이름을 변경할 수 있기 때문에 그들의 Player.UserId를 사용해야 합니다.
플레이어 개체와 작업하기 위한 서비스에는 여러 유사한 방법이 있습니다. 해당 메서드를 사용하십시오:
- Players:GetPlayers()를 사용하여 현재 플레이어 개체의 테이블을 가져올 수 있습니다. 다시 말하지만, Instance:GetChildren() 대신 이를 사용하십시오.
- 마찬가지로, 를 사용하여 플레이어 개체를 제거하는 것을 감지할 수 있으며, 이는 플레이어가 제거되기 전에 발생하는 것으로, 플레이어가 제거된 후에 발생하는 대신 사용됩니다.제거 또는 제거 중에 제거될 수 있는 플레이어에 대한 정보를 저장하는 경우 중요합니다.
코드 샘플
이 코드 샘플은 Roblox의 기본 플레이어 목록 UI에서 리더보드 상태 값의 생성을 보여줍니다.0부터 시작하는 "점수" 리더스탯을 생성합니다.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- 리더스탯용 컨테이너 생성
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- 리더스탯 값 하나 만들기
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- 플레이어에 추가(표시)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
요약
속성
플레이어의 계정 나이(일)를 설명합니다.
모바일 장치를 사용하는 플레이어의 캐릭터가 장애물을 치면 자동으로 점프하는지 여부를 결정합니다.
플레이어의 카메라가 확대할 수 있는 최대 거리.
플레이어의 카메라가 확대할 수 있는 최소 거리.
카메라의 모드를 첫 번째 또는 세 번째 사람으로 변경합니다.
플레이어가 생성될 때 캐릭터의 모양이 로드되는지 여부를 결정합니다. 거짓이면 플레이어가 기본 모양으로 생성됩니다.
A Model 플레이어에 의해 제어되는 플레이어에 포함된 Humanoid 신체 부위, 스크립트 및 기타 개체.
플레이어의 character에 사용되는 캐릭터 모양이 사용된 계정의 사용자 ID를 결정합니다.
기본 카메라가 카메라와 플레이어 사이의 개체를 처리하는 방법을 설정합니다.
Roblox의 데스크톱 버전을 사용할 때 플레이어의 카메라 이동 모드를 결정합니다.
Roblox의 데스크톱 버전을 사용할 때 플레이어의 캐릭터 이동 모드를 결정합니다.
플레이어가 마우스 잠금을 전환할 수 있는지 여부를 결정합니다.
터치 장치를 사용할 때 플레이어의 카메라 이동 모드를 결정합니다.
터치 장치를 사용할 때 플레이어의 캐릭터 이동 모드를 결정합니다.
플레이어와 관련된 UserId의 표시 이름.
플레이어가 플레이어에 의해 게임에 따라온 사용자 ID를 설명합니다.
플레이어 클라이언트 게임플레이가 현재 일시 중지되었는지 여부.
플레이어에게 확인된 배지가 있는지 여부를 나타냅니다.
이 플레이어가 다른 휴머노이드의 체력 바를 볼 수 있는 거리를 설정합니다. 0으로 설정하면 체력 바가 표시되지 않습니다.
이 속성은 로컬 플레이어가 Roblox 계정에 설정한 지역 아이디를 표시합니다.
계정의 구성원 유형을 설명합니다.
이 플레이어가 다른 휴머노이드의 이름을 볼 수 있는 거리를 설정합니다. 0으로 설정하면 이름이 은폐됩니다.
플레이어가 특정 팀에 있는지 여부를 결정합니다.
파티가 소속된 고유 식별자입니다. a Player 속해 있습니다.
부품을 중심으로 복제를 집중시킵니다.
설정되면 플레이어가 지정된 SpawnLocation에서 재생성됩니다.
플레이어가 연결된 팀을 결정합니다.
플레이어가 연결된 팀을 결정합니다.
모든 사용자 계정에 할당된 고유 식별 정수입니다.
메서드
플레이어의 캐릭터에서 모든 액세서리와 다른 캐릭터 모양 개체를 제거합니다.
문자의 머리와 지정된 Vector3 지점 사이의 거리를 반환합니다. 플레이어에 문자가 없는 경우 0을 반환합니다.
경험에 어떻게 참여하는지 설명하는 정보가 포함된 사전을 반환합니다 Player.
클라이언트가 사용하는 마우스를 반환합니다.
고립된 네트워크 대기 시간을 초 단위로 반환합니다.
플레이어의 캐릭터 모양이 로드되었는지 여부를 반환합니다.
플레이어가 구체적이고 실제 세계 신호로 확인되는지 여부를 반환합니다.
플레이어를 게임에서 강제로 분리하고, 선택적으로 메시지를 제공합니다.
플레이어의 캐릭터가 정지하거나 플레이어에 의해 중단될 때까지 지정된 방향으로 걷도록 합니다(컨트롤을 사용하여).
플레이어의 계정 나이를 설정합니다.
플레이어가 필터링된 채팅을 보는지 여부를 설정하거나 일반 채팅을 보는지 여부를 설정합니다.
온라인 친구 사전을 반환합니다.
그룹에서 플레이어의 순위를 0부터 255 사이의 정수로 반환하며, 0은 멤버가 아니고 255는 그룹의 소유자입니다.
그룹에서 플레이어의 역할을 문자열로 반환하거나 플레이어가 그룹의 일부가 아니면 "게스트"로 반환합니다.
플레이어가 사용자에게 지정된 Player.UserId의 친구인지 확인합니다.
플레이어가 지정된 ID의 그룹 멤버인지 확인합니다.
플레이어를 위한 새 캐릭터를 생성하고 이전 캐릭터를 제거합니다. 또한 플레이어의 Backpack 및 PlayerGui를 지웁니다.
서버가 지정된 위치 주변의 플레이어에게 스트리밍하는 요청.
이벤트
플레이어의 캐릭터가 스폰하거나 리스폰하면 발사됩니다.
전체 모양의 Player.Character가 삽입되면 발생합니다.
플레이어의 캐릭터가 제거되기 바로 전에 해고됩니다.
Roblox가 제공한 채팅 바를 사용하여 게임 내에서 플레이어가 채팅할 때 발생합니다.
이 이벤트는 게임 엔진이 player를 비활성으로 분류한 후 약 2분 발생합니다.시간은 그 시점부터 지난 초 수입니다.
플레이어의 TeleportState가 변경될 때 발사됩니다.
속성
AccountAge
코드 샘플
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- 1주
local MIN_AGE_VETERAN = 365 -- 1년
-- 이 함수는 BillboardGui를 사용하여 텍스트가 있는 부분을 표시합니다
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- 부모 채우기
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- 부품에 추가
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- 이 플레이어가 생성되는 것을 감지하기
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
AutoJumpEnabled
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- 업데이트 버튼 텍스트 변경
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- 플레이어의 캐릭터에 속성을 반영하세요, 있는 경우
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- 자동 점프 전환
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- 다른 모든 것 업데이트
update()
end
button.Activated:Connect(onActivated)
update()
CameraMaxZoomDistance
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMinZoomDistance
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMode
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
Character
CharacterAppearanceId
코드 샘플
local Players = game:GetService("Players")
local disguiseCommand = "/disguise "
local function onPlayerChatted(player, message)
if message:sub(1, disguiseCommand:len()):lower() == disguiseCommand:lower() then
local input = message:sub(disguiseCommand:len() + 1)
local id = tonumber(input)
if not id then -- 숫자를 분석할 수 없어요, 아마 대신 사용자 이름을 입력했을 거예요
pcall(function() -- 이 호출은 때때로 실패할 수 있습니다!
id = Players:GetUserIdFromNameAsync(input) -- 이름에서 ID 가져오기
end)
end
if id then
-- 캐릭터 모양을 설정한 다음 재생성
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- 입력에서 ID를 가져올 수 없었습니다
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevCameraOcclusionMode
DevComputerCameraMode
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on computers to classic
player.DevComputerCameraMode = Enum.DevComputerCameraMovementMode.Classic
DevComputerMovementMode
DevEnableMouseLock
코드 샘플
local Players = game:GetService("Players")
local function toggleMouseLock(player)
player.DevEnableMouseLock = not player.DevEnableMouseLock
if player.DevEnableMouseLock then
print("Mouse lock is available")
else
print("Mouse lock is not available")
end
end
local function onPlayerChatted(player, message, _recipient)
if message == "mouselock" then
toggleMouseLock(player)
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevTouchCameraMode
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on mobile devices to classic
player.DevTouchCameraMovementMode = Enum.DevTouchCameraMovementMode.Classic
DevTouchMovementMode
DisplayName
FollowUserId
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local screenGui = Instance.new("ScreenGui")
screenGui.Parent = player:WaitForChild("PlayerGui")
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local textLabel = Instance.new("TextLabel")
textLabel.Parent = screenGui
textLabel.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if textLabel then
textLabel:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GameplayPaused
HasVerifiedBadge
HealthDisplayDistance
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
MembershipType
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- 프리미엄 멤버에 대해 특정 조치 취하기
end
NameDisplayDistance
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
Neutral
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end
PartyId
코드 샘플
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId ~= "" then
print("Player is in a party with ID: " .. partyId)
else
warn("Player is not in a party")
end
end)
ReplicationFocus
코드 샘플
local Players = game:GetService("Players")
local PLAYER_NAME = "polarpanda16"
local player = Players:WaitForChild(PLAYER_NAME)
local part = Instance.new("Part")
part.Parent = workspace
part.Name = "ReplicationFocusPart"
part.Anchored = true
player.ReplicationFocus = part
RespawnLocation
코드 샘플
local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- listen for the spawn being touched
spawnLocation.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character then
local player = Players:GetPlayerFromCharacter(character)
if player and player.RespawnLocation ~= spawnLocation then
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- make sure the character isn't dead
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("spawn set")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- look through the workspace for spawns
for _, descendant in pairs(workspace:GetDescendants()) do
if descendant:IsA("SpawnLocation") then
if descendant.Name == "FirstSpawn" then
firstSpawn = descendant
end
addSpawn(descendant)
end
end
local function playerAdded(player)
player.RespawnLocation = firstSpawn
end
-- listen for new players
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end
StepIdOffset
Team
코드 샘플
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
TeamColor
코드 샘플
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
ThirdPartyTextChatRestrictionStatus
UserId
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local player = Players:GetPlayerByUserId(1)
if player then
print("Player with userId 1 is in this server! Their name is: " .. player.Name)
else
print("Player with userId 1 is not in this server!")
end
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local OWNER_ID = 212423 -- can use game.CreatorId for published places
local BADGE_ID = 1
local ownerInGame = false
local function playerAdded(newPlayer)
if newPlayer.UserId == OWNER_ID then
-- if new player is the owner, set ownerInGame to true and give everyone the badge
ownerInGame = true
for _, player in pairs(Players:GetPlayers()) do
-- don't award the owner
if player ~= newPlayer then
BadgeService:AwardBadge(player.UserId, BADGE_ID)
end
end
elseif ownerInGame then
-- if the owner is in the game, award the badge
BadgeService:AwardBadge(newPlayer.UserId, BADGE_ID)
end
end
local function playerRemoving(oldPlayer)
if oldPlayer.UserId == OWNER_ID then
ownerInGame = false
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerRemoving:Connect(playerRemoving)
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local goldDataStore = DataStoreService:GetDataStore("Gold")
local STARTING_GOLD = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats
local success, result = pcall(function()
return goldDataStore:GetAsync(playerKey) or STARTING_GOLD
end)
if success then
gold.Value = result
else
-- Failed to retrieve data
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
메서드
ClearCharacterAppearance
반환
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local function onChildRemoved(child)
print(child.ClassName, "removed from character")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> BodyColors removed from character
--> ShirtGraphic removed from character
--> Shirt removed from character
--> Pants removed from character
--> CharacterMesh removed from character
--> Hat removed from character
--> Shirt removed from character
DistanceFromCharacter
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
반환
코드 샘플
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local analyticsStore = DataStoreService:GetDataStore("Analytics")
local ALLOWED_SOURCES = {
"twitter",
"youtube",
"discord",
}
local function onPlayerAdded(player)
local source = player:GetJoinData().LaunchData
-- check if the provided source is valid
if source and table.find(ALLOWED_SOURCES, source) then
-- update the data store to track the source popularity
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "joined from", source, "- total:", result)
else
warn("Failed to record join source: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
local textBox = script.Parent
local function generateReferralURL(player)
return DIRECT_JOIN_URL:format(game.PlaceId, player.UserId)
end
local function highlightAll()
if -- avoid recursive property updates
textBox:IsFocused() and not (textBox.SelectionStart == 1 and textBox.CursorPosition == #textBox.Text + 1)
then
textBox.SelectionStart = 1
textBox.CursorPosition = #textBox.Text + 1
end
end
textBox.Focused:Connect(highlightAll)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
textBox.TextEditable = false
textBox.ClearTextOnFocus = false
textBox.Text = generateReferralURL(player)
local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- convert the table to a string
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- escape potentially invalid characters, such as spaces
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- report character limit error
return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "Hello!",
urlCreationDate = os.time(),
magicNumbers = {
534,
1337,
746733573,
},
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("failed to encode launch data: " .. encodedData)
end
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- attempt to decode the data
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "joined with data:", result)
else
-- this is probably due to the user messing with the URL
warn("Failed to parse launch data:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
local function isPlaceIdApproved(placeId)
for _, id in pairs(approvedPlaceIds) do
if id == placeId then
return true
end
end
return false
end
local function onPlayerAdded(player)
local joinData = player:GetJoinData()
-- verify this data was sent by an approved place
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " is on level " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetMouse
반환
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onButton1Down()
print("Button 1 is down")
end
mouse.Button1Down:Connect(onButton1Down)
HasAppearanceLoaded
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local loaded = player:HasAppearanceLoaded()
print(loaded)
while not loaded do
loaded = player:HasAppearanceLoaded()
print(loaded)
task.wait()
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsVerified
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player:IsVerified())
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Move
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
-- Wait for the player's character and humanoid, which must exist before calling :Move()
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
character:WaitForChild("Humanoid")
-- The player will move until they are 50 studs away from the camera's position at the time of running
localPlayer:Move(Vector3.new(0, 0, -50), true)
SetAccountAge
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- 1주
local MIN_AGE_VETERAN = 365 -- 1년
-- 이 함수는 BillboardGui를 사용하여 텍스트가 있는 부분을 표시합니다
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- 부모 채우기
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- 부품에 추가
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- 이 플레이어가 생성되는 것을 감지하기
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetFriendsOnline
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnline, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("Failed to get online players: " .. result)
end
GetRankInGroup
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:GetRankInGroup(2) == 255 then
print("Player is the owner of the group, 'LOL'!")
else
print("Player is NOT the owner of the group, 'LOL'!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetRoleInGroup
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsFriendsWith
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is connections with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsInGroup
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsInGroup(7) then
print("Player is in the Roblox Fan club!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacter
반환
코드 샘플
local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacter()
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacterWithHumanoidDescription
매개 변수
반환
코드 샘플
local Players = game:GetService("Players")
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local humanoidDescription = Instance.new("HumanoidDescription")
humanoidDescription.HatAccessory = "2551510151,2535600138"
humanoidDescription.BodyTypeScale = 0.1
humanoidDescription.ClimbAnimation = 619521311
humanoidDescription.Face = 86487700
humanoidDescription.GraphicTShirt = 1711661
humanoidDescription.HeadColor = Color3.new(0, 1, 0)
player:LoadCharacterWithHumanoidDescription(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)
이벤트
CharacterAdded
매개 변수
코드 샘플
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " has spawned")
end
local function onCharacterRemoving(character)
print(character.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This table maps "Player" objects to Vector3
local respawnLocations = {}
local function onCharacterAdded(character)
local player = Players:GetPlayerFromCharacter(character)
-- Check if we saved a respawn location for this player
if respawnLocations[player] then
-- Teleport the player there when their HumanoidRootPart is available
local hrp = character:WaitForChild("HumanoidRootPart")
-- Wait a brief moment before teleporting, as Roblox will teleport the
-- player to their designated SpawnLocation (which we will override)
RunService.Stepped:wait()
hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
end
end
local function onCharacterRemoving(character)
-- Get the player and their HumanoidRootPart and save their death location
local player = Players:GetPlayerFromCharacter(character)
local hrp = character:FindFirstChild("HumanoidRootPart")
if hrp then
respawnLocations[player] = hrp.Position
end
end
local function onPlayerAdded(player)
-- Listen for spawns/despawns
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
local function onPlayerRemoved(player)
-- Forget the respawn location of any player who is leaving; this prevents
-- a memory leak if potentially many players visit
respawnLocations[player] = nil
end
-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
-- save another right after
Players.PlayerAdded:Connect(onPlayerAdded)
Players.ChildRemoved:Connect(onPlayerRemoved)
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local function destroyAccessory(object)
if object:IsA("Hat") or object:IsA("Accessory") then
object:Destroy()
end
end
local function onCharacterAdded(character)
-- 액세서리를 제거하기 전에 잠시 기다려 피하십시오
-- “예기치 않게 ___ 부모를 NULL로 설정” 경고
RunService.Stepped:Wait()
-- 플레이어의 캐릭터에서 기존 액세서리를 확인
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- 모자는 캐릭터에 잠시 후에 추가될 수 있습니다
-- CharacterAdded 화재가 발생하므로 ChildAdded를 사용하는 사람들을 듣습니다
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
CharacterAppearanceLoaded
매개 변수
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)
CharacterRemoving
매개 변수
코드 샘플
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
매개 변수
코드 샘플
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onChatted(message)
-- do stuff with message and player
print(message)
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Idled
매개 변수
코드 샘플
local Players = game:GetService("Players")
local function onIdled(idleTime)
print(`Player has been idle for {idleTime} seconds`)
if idleTime > 900 then
-- warn player that they've been idle for 15 minutes
-- and will be disconnected in another 5
end
end
Players.LocalPlayer.Idled:Connect(onIdled)
OnTeleport
매개 변수
코드 샘플
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local playerOnTeleport = player
player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
if teleportState == Enum.TeleportState.Started then
print("Teleport started (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
end
end)
end)