Player
*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.
Một đối tượng Người chơi là một khách hàng hiện đang kết nối.Các đối tượng này được thêm vào dịch vụ Players khi một người chơi mới kết nối, sau đó được xóa khi họ cuối cùng kết nối từ máy chủ.
Thuộc tính Instance.Name phản ánh tên người dùng của người chơi.Khi lưu thông tin về một người chơi, bạn nên sử dụng Player.UserId của họ vì có thể một người chơi có thể thay đổi tên người dùng của họ.
Có một số phương pháp tương tự trong dịch vụ để làm việc với các đối tượng Người chơi. Sử dụng chúng vượt qua các phương pháp tương ứng của chúng:
- Bạn có thể nhận được một bảng các đối tượng Người chơi hiện tại bằng cách sử dụng Players:GetPlayers() ; một lần nữa, sử dụng nó thay cho Instance:GetChildren() .
- Để phát hiện sự thêm của các đối tượng Người chơi, được khuyến nghị sử dụng sự kiện Players.PlayerAdded (thay vì Instance.ChildAdded trên dịch vụ Players).
- Tương tự, bạn có thể phát hiện việc xóa các đối tượng Người chơi bằng cách sử dụng , được kích hoạt chỉ trước khi Người chơi bị xóa (thay vì được kích hoạt sau khi)Điều này là quan trọng nếu bạn đang lưu thông tin về người chơi có thể bị xóa hoặc dọn sạch trong quá trình xóa.
Mẫu mã
Ví dụ mã này cho thấy việc tạo các giá trị chỉ số bảng xếp hạng trong UI danh sách người chơi mặc định của Roblox.Nó tạo ra một leaderstat "Điểm" bắt đầu tại 0.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Tạo một thùng chứa cho leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Tạo một giá trị leaderstat
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Thêm vào người chơi (hiển thị nó)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
Tóm Tắt
Thuộc Tính
Mô tả tuổi tài khoản của người chơi trong các ngày.
Xác định xem nhân vật của một người chơi sử dụng thiết bị di động có tự động nhảy lên khi va chạm với chướng ngại vật hay không.
Khoảng cách tối đa mà máy ảnh của người chơi được phép phóng to.
Khoảng cách tối thiểu mà camera của người chơi được phép phóng to.
Thay đổi chế độ của camera thành người thứ nhất hoặc người thứ ba.
Xác định xem liệu sự xuất hiện của nhân vật sẽ được tải khi người chơi xuất hiện. Nếu là false, người chơi sẽ xuất hiện với một sự xuất hiện mặc định.
Một Model được kiểm soát bởi người chơi chứa một Humanoid , các bộ phận cơ thể, các kịch bản và các đối tượng khác.
Xác định ID người dùng của tài khoản mà nhân vật xuất hiện của nó được sử dụng cho một người chơi character .
Xác định cách camera mặc định xử lý các đối tượng giữa camera và người chơi.
Xác định chế độ di chuyển máy ảnh của người chơi khi sử dụng phiên bản máy tính của Roblox.
Xác định chế độ di chuyển nhân vật của người chơi khi sử dụng phiên bản máy tính của Roblox.
Xác định xem người chơi có thể bật/tắt khóa chuột không.
Xác định chế độ di chuyển máy ảnh của người dùng khi sử dụng thiết bị cảm ứng.
Xác định chế độ di chuyển nhân vật của người chơi khi sử dụng thiết bị cảm ứng.
Tên hiển thị của UserId liên quan đến Player.
Mô tả ID người dùng của người chơi đã theo dõi vào một trò chơi bởi một người chơi.
Liệu trò chơi bên khách của người chơi hiện đang bị tạm dừng.
Chỉ ra nếu một người chơi có một Huy hiệu đã xác minh.
Đặt khoảng cách mà người chơi này sẽ nhìn thấy các thanh sức khỏe của các Humanoid khác. Nếu đặt thành 0, các thanh sức khỏe sẽ không được hiển thị.
Thuộc tính này hiển thị ID khu vực mà người chơi địa phương đã đặt cho tài khoản Roblox của họ.
Mô tả loại thành viên của tài khoản.
Đặt khoảng cách mà người chơi này sẽ nhìn thấy tên của các Humanoid khác. Nếu được đặt thành 0, các tên sẽ được ẩn.
Xác định xem người chơi có ở trong một đội cụ thể hay không.
Một nhận dạng duy nhất của bên tham gia mà một Player thuộc về.
Đặt phần tập trung sao chép xung quanh.
Nếu được đặt, người chơi sẽ hồi sinh tại điểm SpawnLocation đã cho.
Xác định đội mà một Người chơi được liên kết.
Xác định đội mà một Người chơi được liên kết.
Một số nhận dạng duy nhất được gán cho tất cả các tài khoản người dùng.
Phương Pháp
Loại bỏ tất cả các phụ kiện và các đối tượng xuất hiện nhân vật khác từ nhân vật của người chơi.
Trả về khoảng cách giữa đầu nhân vật và điểm Vector3 đã cho. Trả về 0 nếu người chơi không có nhân vật.
Trả về một từ điển chứa thông tin mô tả cách Player tham gia vào trải nghiệm.
Trả về chuột đang được sử dụng bởi khách hàng.
Trả về thời gian trễ mạng cách ly trong giây lát.
Trả về việc có hay không có sự xuất hiện của nhân vật của người chơi đã được tải.
Trả về xem người chơi có được xác minh bằng các tín hiệu cụ thể, thế giới thực hay không.
Bắt buộc người chơi tách khỏi trò chơi, tùy chọn cung cấp một thông điệp.
Gây ra nhân vật của người chơi đi theo hướng đã cho cho đến khi dừng lại, hoặc bị ngắt bởi người chơi (bằng cách sử dụng điều khiển của họ).
Đặt tuổi tài khoản của người chơi.
Xác định xem người chơi có nhìn thấy trò chuyện lọc hay không, thay vì trò chuyện bình thường.
Trả về một từ điển của bạn bè trực tuyến.
Trả về thứ hạng của người chơi trong nhóm như một số nguyên từ 0 đến 255, trong đó 0 là thành viên không và 255 là chủ nhân của nhóm.
Trả vai trò của người chơi trong nhóm dưới dạng chuỗi hoặc "Khách" nếu người chơi không thuộc nhóm.
Kiểm tra xem một người chơi có phải là bạn của người dùng với Player.UserId được cho.
Kiểm tra xem một người chơi có phải là thành viên của một nhóm với ID đã cho hay không.
Tạo một nhân vật mới cho người chơi, loại bỏ cái cũ. Cũng xóa Backpack và PlayerGui của người chơi.
Tạo một avatar để nó có mọi thứ được trang bị trong đã qua HumanoidDescription .
Yêu cầu mà máy chủ phát trực tiếp cho người chơi xung quanh vị trí được định.
Sự Kiện
Bị sa thải khi nhân vật của một người chơi xuất hiện hoặc hồi sinh.
Bắt lửa khi toàn bộ xuất hiện của một Player.Character đã được chèn vào.
Bị sa thả ngay trước khi nhân vật của người chơi bị xóa bỏ.
Bắt lửa khi một người chơi trò chuyện trong trò chơi bằng thanh trò chuyện được cung cấp bởi Roblox.
Sự kiện này bắt lửa khoảng hai phút sau khi lớp động cơ trò chơi xếp hạng player là nhàn rỗi.Thời gian là số giây đã trôi qua kể từ điểm đó.
Bị sa thải khi TeleportState của một người chơi thay đổi.
Thuộc Tính
AccountAge
Mẫu mã
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- một tuần
local MIN_AGE_VETERAN = 365 -- một năm
-- Chức năng này đánh dấu một phần có văn bản bằng cách sử dụng 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) -- Điền cha mẹ
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Thêm vào phần
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)
-- Lắng nghe cho người chơi này xuất hiện
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
AutoJumpEnabled
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Cập nhật văn bản nút
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Phản ánh thuộc tính trong nhân vật của người chơi, nếu họ có một
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Bật/tắt nhảy tự động
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Cập nhật tất cả những thứ khác
update()
end
button.Activated:Connect(onActivated)
update()
CameraMaxZoomDistance
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMinZoomDistance
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMode
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
Character
CharacterAppearanceId
Mẫu mã
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 -- Số không thể phân tích, có lẽ họ đã nhập tên người dùng thay vào đó
pcall(function() -- Cuộc gọi này có thể thất bại đôi khi!
id = Players:GetUserIdFromNameAsync(input) -- Lấy ID từ tên
end)
end
if id then
-- Chỉnh sửa xuất hình nhân vật rồi hồi sinh
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- Chúng tôi không thể nhận được một ID từ nhập của họ
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevCameraOcclusionMode
DevComputerCameraMode
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
MembershipType
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- Take some action specifically for Premium members
end
NameDisplayDistance
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
Neutral
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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
Mẫu mã
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)
Phương Pháp
ClearCharacterAppearance
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
Lợi Nhuận
Mẫu mã
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
Lợi Nhuận
Mẫu mã
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
Lợi Nhuận
Mẫu mã
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
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- một tuần
local MIN_AGE_VETERAN = 365 -- một năm
-- Chức năng này đánh dấu một phần có văn bản bằng cách sử dụng 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) -- Điền cha mẹ
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Thêm vào phần
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)
-- Lắng nghe cho người chơi này xuất hiện
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetFriendsOnline
Tham Số
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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
Lợi Nhuận
Mẫu mã
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
Tham Số
Lợi Nhuận
Mẫu mã
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)
Sự Kiện
CharacterAdded
Tham Số
Mẫu mã
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)
-- Chờ một lúc ngắn trước khi gỡ bỏ phụ kiện để tránh
-- Cảnh báo "Something unexpectedly set ___ parent to NULL"
RunService.Stepped:Wait()
-- Kiểm tra các phụ kiện hiện có trong nhân vật của người chơi
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Nón có thể được thêm vào nhân vật một lúc sau
-- Nhân vật được thêm vào, vì vậy chúng tôi lắng nghe những người sử dụng ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
CharacterAppearanceLoaded
Tham Số
Mẫu mã
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- Tất cả các phụ kiện đã được tải tại thời điểm này
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Hãy chắc chắn rằng chúng ta cắt kết nối với người chơi sau khi họ rời đi
-- để cho phép người chơi nhận được rác được thu thập
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)
CharacterRemoving
Tham Số
Mẫu mã
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
Tham Số
Mẫu mã
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
Tham Số
Mẫu mã
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
Tham Số
Mẫu mã
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)