Player

Pokaż przestarzałe

*Ta zawartość została przetłumaczona przy użyciu narzędzi AI (w wersji beta) i może zawierać błędy. Aby wyświetlić tę stronę w języku angielskim, kliknij tutaj.

Obiekt Gracz jest klientem, który jest obecnie połączony. Te obiekty są dodawane do usługi Players , gdy nowy gracz się połączy, a następnie usunięte, gdy ostatecznie odłączy się od serwera.

Właściwość Instance.Name odzwierciedla nazwa gracz. Podczas zapisywania informacji o graczpowinieneś używać ich Player.UserId, ponieważ możliwe jest, że użytkownik może zmienić nazwa użytkownika.

Istnieje kilka podobnych metod w Players usłudze do pracy z obiektami gracza. Użyj tych nad ich odpowiednich metod Instance :

Przykłady kodu

This code sample demonstrates the creation of leaderboard stat values in Roblox's default player list UI. It creates a "Score" leaderstat that starts at 0.

Leaderstats

local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Create a container for leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Create one leaderstat value
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Add to player (displaying it)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)

Podsumowanie

Właściwości

Metody

Zdarzenia

Właściwości

AccountAge

Tylko do odczytu
Bez replikacji
Odczyt równoległy

AgeKonto to właściwość Player, która opisuje, ile dni temu zostało zarejestrowane konto gracza. Ustawione jest przy użyciu funkcji Player:SetAccountAge(), która nie może być dostępna przez skrypty.

Właściwość ta jest przydatna do okazania nowym graczom Roblox treści, która może być wyświetlana kondycyjnie, takiej jak tutoriale.

Przykłady kodu

This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.

Account Age Mark

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a 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) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
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)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

AutoJumpEnabled

Odczyt równoległy

Właściwość AutoJumpEnabled określa, czy Player.Character Class.Player używającego urządzenia mobilnego będzie automatycznie skakiować, gdy dotknie ono przeszkody. To może ułatwić poziomy do przeglądania po poziomie, gdy jest używany na urządzeniemobilnym.

Gdy gracz dołącza do gry, wartość StarterPlayer.AutoJumpEnabled określa początkowy stan tej właściwości. Następnie ta właściwość określa wartość Humanoid.AutoJumpEnabled właściwości Player.Character podczas wchodzenia. Innymi słowy

Przykłady kodu

This code sample is meant for a TextButton. It allows the player to toggle the auto-jumping behavior while on a mobile device.

Auto-Jump Toggle

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()

CameraMaxZoomDistance

Odczyt równoległy

Właściwość CameraMaxZoomDistance Player ustawia maksymalną odległość w studsach, jaką może mieć kamera od postaci z domyślnymi kamerkami.

Innymi słowy, kontroluje maksymalną odległość, jaką kamera gracza może skorygować.

Domyślna wartość tego właściwości jest ustawiona przez StarterPlayer.CameraMaxZoomDistance. Jeśli ta wartość zostanie ustawiona na niższą wartość niż Player.CameraMinZoomDistance, zostanie ona zwiększona do CameraMinZoomDistance.

Przykłady kodu

The example demonstrates how to set a player's camera minimum and maximum zoom distance.

In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.

Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.

To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMinZoomDistance

Odczyt równoległy

Właściwość CameraMinZoonDistance Player ustawia minimalną odległość w studsach, z której kamera może być od kamery z domyślnymi kamerkami.

Innymi słowy, kontroluje minimalną odległość, jaką kamera gracza może zoomować.

Domyślną wartością tego właściwości jest ustawiony przez StarterPlayer.CameraMinZoomDistance. Jeśli ta wartość jest ustawiona na większą niż Player.CameraMaxZoomDistance zostanie zmniejszona do CameraMaxZoomDistance.

Przykłady kodu

The example demonstrates how to set a player's camera minimum and maximum zoom distance.

In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.

Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.

To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMode

Odczyt równoległy

Właściwość KameraModuł ustawia tryb kamerze gracza, domyślnie na trzeci osobnik.

Trzecia osoba

W trybie postaci w trzeciej osobie domyślnej ( Enum.CameraMode.Classic ) widoczny jest postać w kamery. W tym trybie domyślnym zachowaniem jest:

  • Gracze mogą prawić kliknąć i przeciągnąć (myszka), naciąć i przeciągnąć (telefon), użyć współczynnika rotacji (gamepad), lub naciąć lewą / prawą strzałkę (klawiatura), aby obrócić kamerę wokół ich postaci.
  • Gdy gracz porusza swoją postacią, to twarzy w kierunku odpowiednim ruchu.
  • Gracze mogą przyjmować i oddawać darmową skalę, nawet do pierwszej osoby w pełnym skali w.

Pierwsza osoba

W trybie pierwszej osoby ( Enum.CameraMode.LockFirstPerson ) kamerka gracza jest skalowana w całym kadrze. Chyba, że istnieje widoczna GUI z własnością GuiButton.Modal ustawioną na true , ruszając myszką, dotykając na telefonie lub używając dodatkowego joysticka na gamepadzie, k

Przykłady kodu

This example demonstrates how to change the character's CameraMode to first person using the LockFirstPerson value of the Enum.CameraMode enum.

Playing in First Person

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson

CanLoadCharacterAppearance

Odczyt równoległy

Właściwość CanLoadCharacterAppearance Player określa, czy wygląd postaci zostanie załadowany, gdy gracz się pojawi. Domyślną wartość tej właściwości ustawia StarterPlayer.LoadPlayerAppearance.

Jeśli prawda, postać załadować będzie wygląd gracza odpowiadającego Player.CharacterAppearanceId gracza.

Jeśli fałszywy , gracz pojawi się z domyślnym wyglądem - model postaci czarnego postaci bez żadnych czapek, koszul, spodni itp.

Próbując ustawić właściwość po pojawieniu się postaci nie zmieni postaci, musisz wywołać Player:LoadCharacter(), aby załadować nowy wygląd.

Przykłady kodu

This example demonstrates how to disable loading a player's character appearance. Instead, the player loads as a grey model without any hats, shirts, pants, etc.

This is useful for games using custom clothing and accessories.

Note that if the character has already spawned, this change will not take affect until the player respawns or the Player:LoadCharacter() function is called.

Disabling a Player's Appearance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false

Character

Odczyt równoległy

Właściwość Postać zawiera odniesienie do Model zawierającego Humanoid, części ciała, skrypty i inne obiekty w

Początkowo właściwość ta jest nil i jest ustawiona, gdy postać gracza po raz pierwszy się pojawia. Użyj wydarzenia Player.CharacterAdded, aby wykryć, gdy postać gracza zostanie prawidłowo załadowana, a wydarzenia Player.CharacterRemoving, aby wyk

Uwaga, że LocalScripts, które są sklonowane z StarterGui lub StarterPack do gracza 2>


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
if not character or character.Parent == nil then
character = player.CharacterAdded:Wait()
end

CharacterAppearanceId

Odczyt równoległy

Ten parametr określa ID użytkownika konta, którego postać wygląda na gracza Class.Player.Character . Domyślnie, ten parametr jest Player.Character, który używa awatara gracza, jakim został stworzony na stronie Roblox.

Zmiana tego właściwości na ID użytkownika innego konta spowoduje, że gracz zostanie zespawnowany z wyglądem tego konto(czapki, koszule, spodnie itp).

Gry mogą również zmieniać, czy wygląd postaci gracza jest ładowany w grze poprzez zmianę właściwości StarterPlayer.LoadCharacterAppearance.

Przykłady kodu

This code sample allows players to chat "/disguise xyz", where xyz is a user ID or username, and they will respawn appearing like that account's avatar. Try typing "/disguise 261" or "/disguise Shedletsky"!

Disguise Command

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 -- Number failed to parse, maybe they typed a username instead
pcall(function() -- This call can fail sometimes!
id = Players:GetUserIdFromNameAsync(input) -- Fetch ID from name
end)
end
if id then
-- Set character appearance then respawn
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- We couldn't get an ID from their input
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

DevCameraOcclusionMode

Odczyt równoległy

Definiuje sposób, w jaki domyślne skrypty kamery poruszają obiekty między kamera a kamera subiektu. Ustawione przez StarterPlayer.DevCameraOcclusionMode i nie może być zmienione dla poszczególnych graczy.

Domyślną wartością jest Zoom (0). Zobacz Enum.DevCameraOcclusionMode dla listy dostępnych trybów.

Odczyt równoległy

Właściwość DevComputerCameraMode określa sposób, w jaki gracz porusza kamerę, gdy używa urządzenia z myszką i klawiaturą. Zobacz Enum.DevComputerCameraMovementMode dla opisu każdego dostępnego trybu kamerowego. Ta właściwość nie może być ustawiona za pomocą LocalScript (musi być ustawiona na serwerze za pomocą

Domyślną wartość tego właściwości jest określona przez StarterPlayer.DevComputerCameraMovementMode .

Słowo „komputer” w tej nazwie właściwości odnosi się do nie- TouchEnabled , nie- GamepadEnabled urządzeń.

Gdy ustawiony na Wybór użytkownika , gracz może wybrać pomiędzy dowolnym trybem kontroli (za wyjątkiem Skrypty ) w ustawieniach gry Roblox. W ogólnedobrym pomysłem jest pozwolenie graczom wybrać swój tryb kontroli, aby zwiększyć dostępność.

Możliwe jest utworzenie niestandardowego schemu kontroli ustawiając tę właściwość na Scriptable .

Ta właściwość nie dotyczy graczy, którzy używają włączonego urządzeniedotykowego. Zobacz Player.DevTouchCameraMode zamiast tego.

Przykłady kodu

The example demonstrates how to set a player's camera movement mode for players on a computer.

In this example, we set the camera movement mode to Classic via the Enum.DevComputerCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.

Setting a Player's Camera Movement Mode (Desktop)

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

Odczyt równoległy

Właściwość DevComputerMovementMode określa sposób, w jaki gracz porusza swojego postaci, gdy używa urządzenia z myszką i klawiaturą. Zobacz Enum.DevComputerMovementMode dla opisu każdego trybu ruchu dostępnego. Ta właściwość nie może być ustawiona za pomocą LocalScript (musi być ustawiona na serwerze za pom

Domyślną wartość tego właściwości jest zdeterminowana przez StarterPlayer.DevComputerMovementMode .

Słowo „komputer” w tej nazwie właściwości odnosi się do nie- TouchEnabled urządzeń.

Gdy ustawiony na Wybór użytkownika , gracz może wybrać pomiędzy dowolnym trybem kontroli (za wyjątkiem Skrypty ) w ustawieniach gry Roblox. W ogólne, dobrym pomysłem jest pozwolenie graczom wybrać swój tryb kontroli, aby zwiększyć dostępność.

Możliwe jest utworzenie niestandardowego schemu kontroli ustawiając tę właściwość na Scriptable .

Ta właściwość nie dotyczy graczy używających urządzeniez możliwością dotyku. Zobacz Player.DevTouchMovementMode zamiast tego.

Przykłady kodu

Demonstrates how to set the movement mode for players on computers using the Player.DevComputerMovementMode property.

Setting a Player's Movement Mode (Desktop)

local Players = game:GetService("Players")
local function onPlayerAdded(player: Player)
-- Set the player's movement mode on desktop devices to click-to-move
-- Once set, the player can right click in the game world and the character will move there.
player.DevComputerMovementMode = Enum.DevComputerMovementMode.ClickToMove
end
Players.PlayerAdded:Connect(onPlayerAdded)

DevEnableMouseLock

Odczyt równoległy

Ta właściwość określa, czy gracz jest w stanie przełączyć Mouse zablokowanie poprzez naciśnięcie Shift . Gracz może wyłączyć przełącznik zablokowania myszy w ustawieniach gry Roblox. Domyślnie ta właściwość jest ustawiona na wartość

Gdy ustawiony jest mikropomiar, kursorek gracza jest zablokowany w centrum ekranu. Przesuwanie myszy po orbicie kamery wokół gracza character i znajduje się w tym samym kierunku co camera . Przesunięcie kamery również zdefiniuje widok kamery w okolicy prawego ramienia gracza.

Uwaga, że API związane z zamkiem zmiany stanu przesuwane są w trakcie deprecji, więc zaleca się używanie UserInputService.MouseBehavior zamiast zamkiem myszy.

Przykłady kodu

This code sample demonstrates how to toggle whether mouse lock is available to a player using a chat command. When a player types "mouselock", their ability to toggle mouse lock is toggled. Note that this does not toggle the actual state of mouse lock; rather, it changes whether a player is able to toggle it themselves.

This code can be run by pasting it into a Script within ServerScriptService.

Toggling Mouse Lock Ability

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)
Odczyt równoległy

Właściwość DevTouchCameraMode określa sposób, w jaki gracz porusza kamerę, gdy używa urządzenieTouchEnabled. Patrz Enum.DevTouchCameraMovementMode dla opisu każdego trybu sterowania kamerą dostępnego. Nie można ustawić właściwości używając <

Domyślną wartość tego właściwości jest określona przez StarterPlayer.DevTouchCameraMovementMode .

Gdy ustawiony na Wybór użytkownika , gracz może wybrać pomiędzy dowolnym trybem kontroli (za wyjątkiem Skrypty ) w ustawieniach gry Roblox. W ogólne, dobrym pomysłem jest pozwolenie graczom wybrać swój tryb kontroli, aby zwiększyć dostępność.

Możliwe jest utworzenie niestandardowego schemu kontroli ustawiając tę właściwość na Scriptable .

Ta właściwość nie dotyczy graczy, którzy nie używają włączonego dotykowo urządzenie. Zobacz Player.DevComputerCameraMovementMode zamiast tego.

Przykłady kodu

The example demonstrates how to set a player's camera movement mode.

In this example, we set the camera movement mode to Classic via the Enum.DevTouchCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.

Setting a Player's Camera Movement Mode (Touch)

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

Odczyt równoległy

Właściwość DevTouchMovementMode określa sposób, w jaki gracz porusza swojego postaci, gdy używa urządzenieTouchEnabled. Patrz Enum.DevTouchMovementMode dla opisu każdego trybu ruchu dostępnego. Ta właściwość nie może być ustawiona za pomocą <

Domyślną wartość tego właściwości jest zdeterminowana przez StarterPlayer.DevTouchMovementMode .

Gdy ustawiony na Wybór użytkownika , gracz może wybrać pomiędzy dowolnym trybem kontroli (za wyjątkiem Skrypty ) w ustawieniach gry Roblox. W ogólnedobrym pomysłem jest pozwolenie graczom wybrać swój tryb kontroli, aby zwiększyć dostępność.

Możliwe jest utworzenie niestandardowego schemu kontroli ustawiając tę właściwość na Scriptable .

Ta właściwość nie dotyczy graczy, którzy nie używają urządzeniew pełni włączonego dotykowo. Zobacz Player.DevComputerMovementMode zamiast tego.

Przykłady kodu

The example demonstrates how to set the movement mode for players on touch enabled devices.

In this example, we set the movement mode to Thumbstick via the Enum.DevTouchMovementMode enum. This means that players on touch enabled devices are able to move via a virtual thumbstick on their screen.

Setting a Player's Movement Mode (Touch)

local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevTouchMovementMode = Enum.DevTouchMovementMode.DynamicThumbstick
end)

DisplayName

Odczyt równoległy

DisplayName jest własnością Player, która zawiera nazwę wyświetlaną przez autoryzowanego użytkownika powiązanego z obiektem Player. W przeciwieństwie do imion użytkowników, nazwy wyświetlanie są niepowtarzalnymi nazwami, które gracz wyświetla dla innych. Jeśli u

Notatka:

  • Ponieważ nazwy wyświetlanych są niepowtarzalne, może być dla dwóch graczy w jednej instancji identycznych nazw. Jeśli potrzebujesz unikalnego identyfikatora dla gracza, użyj Player.UserId (który jest statyczny) lub Player.Name (który jest obecnym nazwą użytkownika).
  • Zwierzęta generowane za pomocą Player.LoadCharacter lub przez silnik Roblox będą posiadać ich właściwość Humanoid.DisplayName przypisaną do właściwości Player.DisplayName.
  • Nazwy mogą zawierać znaki niezgodne z polską wersją języka. See UTF-8 for more information on how to work with strings with unicode characters.

FollowUserId

Tylko do odczytu
Bez replikacji
Odczyt równoległy

FollowUserId to właściwość Player, która zawiera Player.UserId użytkownika, którego gracz podążył do gry. Jeśli gracz nie podążył za nikim w grze, ta właściwość będzie 0. Ta właściwość jest użyteczna do alarmowania graczy, którzy podążają za innym graczem w grę.

Możesz uzyskać nazwę gracza podążając używając tego użytkownika ID i funkcji Players:GetNameFromUserIdAsync().

Przykłady kodu

This code sample alerts players if a new player follows the local player into the game. Place this in a LocalScript in StarterPlayerScripts.

Followed Alert

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

Brak dostępu do zabezpieczeń
Odczyt równoległy

Właściwość GameplayPaused wskazuje, czy gracz jest obecnie w stanie zawieszenia w miejscu z włączonym StreamingEnabled . Jest ustawiony na klienta, ale skopiowany na serwer. Aby określić statuszawieszenia, możesz użyć tej właściwości.

Zobacz również:

HasVerifiedBadge

Odczyt równoległy

Właściwość HasVerifiedBadge Player wskazuje, czy gracz ma aktywowany znчок.

HealthDisplayDistance

Odczyt równoległy

Właściwość HealthDisplayDistance Player ustawia odległość w studsach, w których ten gracz będzie widział inne Humanoid bary zdrowia. Jeśli ustawiono na 0, bary zdrowia nie będą wyświetlane. Ta właściwość jest ustawiona na StarterPlayer.HealthDisplayDistance przez domyślnie.

Jeśli widać barwę zdrowia ludoidu, możesz ustawić typ wyświetlania używając Humanoid.DisplayDistanceType .

Przykłady kodu

This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.

This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.

If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.

To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

LocaleId

Ukryte
Tylko do odczytu
Bez replikacji
Odczyt równoległy

Właściwość Player z lokalnym ID pokazuje lokalny identyfikator lokalizacji, który ustawił lokalny gracz dla swojego kontoRoblox. Zawiera strunę z dwóch kodów literowych (na przykład „en-us”) dla lokalizacji.

Można użyć tego, aby określić demografię geograficzną graczy w bazie grze, a jest to również lokalizacja używana do automatycznej lokalizacji (patrz GuiBase2d.AutoLocalize), która jest w grze. Ta właściwość umożliwia dostęp do lokalizacji gracza z serwera.

Zobacz również LocalizationService.RobloxLocaleId , lokalizator lokalizacji używany do lokalizacji treści wewnętrznej. Będzie to inna wartość, gdy Roblox jeszcze nie wspiera lokalnie lokalizatora lokalizacji lokalnej.

Przykłady kodu

This example demonstrates how to check the locale of a local player using the Player.LocaleId property. It prints a string with the two letter locale code for the locale of the local player.

For instance, if the player's local is within the US, the locale will be:

en-us

Checking a Player's Locale

local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)

MembershipType

Tylko do odczytu
Bez replikacji
Odczyt równoległy

Ta właściwość może być czytana tylko z tożsamości (nie może być ustawione na inny wpisywaćczłonkowstwa). Zawiera Enum.MembershipType enkumenium wpisywaćczłonkowstwa konto.

Przykłady kodu

The following example checks whether a player has Premium membership.

Check Player Membership Status

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

Odczyt równoległy

Właściwość StarterPlayer ustawia odległość w studsach, przy której ten gracz będzie widział inne imiona Humanoid. Jeśli właściwość jest ustawiona na 0, imiona są ukryte. Ta właściwość jest ustawiona na StarterPlayer.NameDisplayDistance przez domyślnie.

Jeśli widać barwę zdrowia ludoidu, możesz ustawić typ wyświetlania używając Humanoid.DisplayDistanceType .

Przykłady kodu

This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.

This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.

If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.

To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

Neutral

Odczyt równoległy

Właściwość Neutralna określa, czy gracz jest w konkretnej drużynie.

  • Gdy prawda, gracz nie jest w konkretnej drużynie. Oznacza to również, że właściwość Player.Team będzie nil i kolor Player.TeamColor będzie biały.
  • Gdy fałszywy, gracz jest w drużynie specyficznej. Właściwość Player.Team będzie odpowiadać Team, na której znajduje się gracz, a 1> Class.Player.TeamColor1> .

Przykłady kodu

This example checks if a player is neutral. If the player is neutral, the game prints:

Player is neutral!

If the player is not neutral, the game prints:

Player is not neutral!

Note: Although this example prints the value of the local player's neutral property, you can change the example to get the value for any player.

Checking if a Player is 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

ReplicationFocus

Odczyt równoległy

Właściwość ReplicationFocus Player ustawia część, aby skupić replikację wokół gracza. Różne systemy Roblox, które komunikują się poprzez sieć (takie jak fizyka, przesyłanie i inne) replikują się w różnych szybkościach w zależności od tego, jak blisko obiektów jest fokusu replikacji.

Gdy ta właściwość jest nil, zwraca się do jej domyślnego zachowania, które jest traktowanie lokalnego gracza jego postaci PrimaryPart jako obiektu skupienia.

Ten właściwość powinien być ustawiony tylko na serwerze z Script , a nie LocalScript. Uwaga, że ta właściwość nie zmienia lub aktualizuje własności sieci części.

Przykłady kodu

This example creates a new BasePart and sets the Player's Player.ReplicationFocus to that part.

This demonstrates the functionality of the ReplicationFocus property. You can easily change the part that the focus is set to to change the replication focus.

Setting a Player's Replication Focus

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

Odczyt równoległy

Jeśli ustawiać, gracz będzie respawnować na podanym SpawnLocation . Ta właściwość może być ustawiona tylko poprzez Lua i musi zawierać odniesienie do ważnego SpawnLocation , który musi spełniać następujące kryteria:

Jeśli RespawnLocation nie jest ustawiony na ważną SpawnLocation to wtedy zastosuje się domyślna logika spawningu. Aby uzyskać więcej informacji na ten temat, zobacz stronę dla SpawnLocation .

Alternatywy dla RespawnLocation

Przykłady kodu

This code sample will set the player to always respawn from the last SpawnLocation they touched. New players will respawn from the SpawnLocation named 'FirstSpawn' until they touch a different SpawnLocation.

This is an alternative to using the AllowTeamChangeOnTouch property to switch SpawnLocations and does not require Teams.

Change Spawn on Touch

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

Team

Bez replikacji
Odczyt równoległy

Właściwość Zespół określa obiekt Team w usłudze Class

Przykłady kodu

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

Playing/Spectating Teams

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)

This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".

Join Team Command

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

Odczyt równoległy

Właściwość TeamColor określa, z którym zespołem gracz jest powiązany zgodnie z jego Team.TeamColor . Zmienie tego właściwości zmieni Player.Team według tego, którego zespołu ma tę samą BrickColor dla ich 1>

Często lepszym rozwiązaniem jest ustawienie Player.Team na odpowiedni Team zamiast używania tej właściwości. Ustawienie tej właściwości często prowadzi do powtórzenia tej samej wartości BrickColor dla pewnej drużyny na wielu skryptach; to jest coś, czego chcesz uniknąć, gdy przestrzegasz zasady "N

Przykłady kodu

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

Playing/Spectating Teams

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)

UserId

Odczyt równoległy

Id użytkownika to właściwość Class.Player , która zawiera czytelny identyfikator liczby, który Instance.Name identyfikuje każde konto użytkownika na Roblox. W przeciwieństwie do 1> Class.Instance.Name1> gracza, który może się zmieniać w zależności od obecnego nazwa użytkownikaużytkownika, ta w

Ten parametr jest niezbędny podczas zapisywania/ładowania danych gracza używając GlobalDataStores . Użyj unikalnego klucza gracza, aby każdy gracz miał unikalny klucz.

Przykłady kodu

The below example would print the UserId of every user who entered a game.

Player.UserId

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players:GetPlayerByUserId

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

The following code sample gives an example of a 'met the creator' badge system. This script will award a specified badge (BADGE_ID) to anyone who is in a server at the same time as the user associated with OWNER_ID.

Met the Creator Badge

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)

This code sample retrieves a player's saved gold from a data store and puts the returned value onto the leaderboard. Note that this sample does not save players' gold — it only loads it.

Data Store to Leaderboard

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)

Metody

ClearCharacterAppearance

void

Funkcja ClearCharacterAppearance usuwa wszystkie Accessory, Shirt, Pants, 1> Class.CharacterMesh

Nie usuwa t-shirts , sieci głowicy lub twarzy.


Zwroty

void

Przykłady kodu

How to Clear a Character's Appearance

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

Funkcja DistanceFromCharacter Player zwraca dystans między głową znaku a podanym punktem Vector3. Wynika 0, jeśli gracz nie ma Player.Character.

Przydatny jest to, gdy określa się dystans między innym obiektem lub lokalizacją w gra.

Jeśli chcesz określić dystans między dwoma nieobsługującymi instancjami lub pozycji, możesz użyć obserwuje:


local distance = (position1 - position2).magnitude

Parametry

point: Vector3

Lokalizacja, z której liczona jest odległość gracza.


Zwroty

Dystans w klombach między graczem a lokalizacją.

Przykłady kodu

This example demonstrates how to measure the distance between a player's Player.Character and another location.

This code will print the distance of each player's character from the origin (0, 0, 0):

Measuring the Distance Between a Player and a Position

local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end

GetJoinData

Zwraca słownik zawierający informacje opisujące, jak gracz doświadcza. Słownik zawiera dowolne z następujących poles:


<tbody>
<tr>
<th>Idź do źródła</th>
<td>liczba</td>
<td>The <code>Class.DataModel.GameId</code> of the experience the <code>Player</code> teleported from. Only present if the player teleports to the current experience and if a server calls the teleport function.</td>
</tr>
<tr>
<th>Idź do źródła</th>
<td>liczba</td>
<td>Class.DataModel.PlaceId of the place the <code>Player</code> teleported from. Only present if the player teleports to the current place and a server calls the teleport function.</td>
</tr>
<tr>
<th>Zgłoszony przez gracza</th>
<td>liczba</td>
<td>Class.Player.UserId gracza, który zaprosił bieżącego gracza do doświadczenia. Użyj tych danych, aby zidentyfikować referera i związać zasadę nagrody.</td>
</tr>
<tr>
<th>Członkowie</th>
<td>masz</td>
<td>Materiały <code>Class.Player.UserId</code> zawierające liczby użytkowników teleportowanych obok <code>Player</code>. Obecny tylko wtedy, gdy gracz teleportował się jako część grupa.</td>
</tr>
<tr>
<th>Teleportacja danych</th>
<td>wartiant</td>
<td>Odbiera <code>teleportData</code> określoną w oryginalnym teleportować się. Przydatny do udostępniania informacji między serwerami, do których teleportuje się gracz. Tylko prezentuje się, jeśli <code>teleportData</code> została określona i serwer wzywa funkcję teleportacji.</td>
</tr>
<tr>
<th>Dane o uruchomieniu</th>
<td>ciąg</td>
<td>Oczywisty lub zaszyfrowany JSONowy ciąg, który zawiera dane uruchomienia określone w adresie URL <a href="../../../production/promotion/deeplinking.md">深链</a> lub <code>Class.ExperienceInviteOptions.LaunchData</code> .</td>
</tr>
</tbody>
KluczTyp wartościOpis

ZdobądźJoinData i TeleportData

Jeśli serwer inicjuje teleportować sięgracza, to słownik, który ten metodę zwraca, zawiera dane teleportacji gracza. Metoda Player:GetJoinData() może być używana tylko do uzyskania danych teleportacji na serwerze. Aby uzyskać dane na klienta, użyj metody TeleportService:GetLocalPlayerTeleportData().

Oprócz TeleportService:GetLocalPlayerTeleportData() , Player:GetJoinData() dostarcza tylko dane teleportu, które spełniają następujące kryteria bezpieczeństwa:

  • Gwarantujemy, że został wysłany przez serwer Roblox w ciągu ostatnich 48 godzin.
  • Gwarantujemy, że został wysłany z tym Player .
  • SourcePlaceId i SourceGameId gwarantują, że są to miejsca i wszechświaty, z których dane zostały wysłane. Oznacza to, że możesz sprawdzić, że dane o teleportacji pochodzą z zatwierdzonego miejsce.

Ponieważ dane te są przesyłane przez klienta, nadal może być potencjalnie wykorzystywane przez eksploitera. Delikatne dane, takie jak waluta gracza, powinny być przesyłane za pośrednictwem bezpiecznego rozwiązania, takiego jak Przechowywanie pamięci.


Zwroty

Dictionarium zawierające wartości PlaceId i UserId (zobacz tabelę w opisie).

Przykłady kodu

The following example tracks sources of traffic for analytics. By creating URLs with unique launch data for each social platform, you can determine the most popular traffic sources. The sample checks the source against a list of possible samples and discards any invalid sources because users can modify the launch data.

Tracking Traffic Sources

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)

The following example generates a URL with the user's ID used as launch data. It then displays the URL in a read-only text box that makes it easy for the user to copy and share the link with their friends. When a user joins the game using a referral link, you can use the launch data to reward the referrer.

Referral URL Generator

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)

The following example is a function that converts a table into a string you can use as launch data. The provided data is JSON encoded, checked for valid character length, and escaped with percent signs.

Using a Table as Launch Data

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

The following example attempts to decode launch data, using pcall to prevent an error in case the data is corrupt.

Decoding JSON Launch Data

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)

The following code sample is an example of how teleport data can be retrieved on the server using Player:GetJoinData(). This code, when ran in a Script in ServerScriptService, will listen for new Player|Players joining the game. When they join it will retrieve their teleport data (verifying it came from a valid place) to find their current level.

Server TeleportData Example

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

Funkcja GetMouse Player zwraca Mouse używany przez gracz. Instancja miksera można używać do śledzenia wejścia miksera lewego i prawego przycisku myszy i ruchu i lokalizacji.

Usługa UserInputService dostarcza dodatkowe funkcje i wydarzenia do śledzenia wejścia użytkownika - szczególnie dla urządzeń, które nie używają myszy.

Notatka:

  • Ten przedmiot musi być używany w LocalScript , aby działał jak oczekiwano online.
  • Po aktualizacji w lipcu 2014 r. ikona myszy można teraz ustawić za pomocą tego metody.

Zwroty

Przykłady kodu

The below example will print:

Button 1 is down

whenever the Players.LocalPlayer left clicks.

How to Track Mouse Input

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)

GetNetworkPing

Zapis równoległy

GetNetworkPing zwraca izolowaną sieć latency z Player w sekundach. "Ping" to pomiar czasu potrzebnego na wysłanie danych z klienta na serwer, a następnie ponownie. Nie wiąże się to z dezserwowaniem lub przetwarzaniem danych.

Dla strony klienta LocalScripts , ta funkcja może być wywołana tylko na Players.LocalPlayer . Ta funkcja jest użyteczna w identyfikowaniu i debugowaniu problemów, które występują w wysokich sieciach zależności. Jest również użyteczna do maskowania latencji, takiej jak dostosowywanie szybkości rzucania animacji dla projektli.


Zwroty

HasAppearanceLoaded

Funkcja HasAppearanceLoaded Player zwraca, czy ładowanie widoku gracza Player.Character ładowane jest.

Wygląd gracza zawiera elementy, takie jak Shirt gracza, Pants i Accessories.

Przydatne jest ustalenie, czy wygląd gracza załadował się po raz pierwszy po dołączeniu do gry, co można śledzić za pomocą wydarzenia Players.PlayerAdded.


Zwroty

Boolean wskazujący, czy wygląd postaci gracza został załadowany lub nie.

Przykłady kodu

This example prints the result of Player:HasAppearanceLoaded() after a player joins the game until the player's appearance has loaded.

Check if a Player's Appearance Has Loaded

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

Zwraca wartość prawdziwą określającą status weryfikacji gracza. Gdy prawda, gracz jest weryfikowany. Weryfikacja obejmuje, ale nie jest ograniczona do, nie-VOIP numer telefonu lub weryfikacji tożsamości rządowego.

Podczas wdrożenia IsVerified uważaj, aby zagwarantować, że implementacja nie zablokuje niezweryfikowanych użytkowników nieprzypadkowo.

Uwaga, że metoda może być wywołana tylko na serwerze back-end. Wywołanie jej na stronie klienta spowoduje błąd. Ponadto ta metoda zawsze zwraca false w Studio.


Zwroty

Boolean wskazujący, czy gracz jest zweryfikowany.

Przykłady kodu

The following example prints "true" if the player is verified.

Using 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)

Kick

void

Methode Kick() pozwala na ładne odłączenie klienta i możliwość opcjonalnego dostarczania wiadomości użytkownikowi odłączonemu. To użyteczne dla moderowania nadużywających użytkowników. Powinieneś pozwolić tylko zaufanym użytkownikom, którzy ufają, aby ten metod działał na innych użytkowników.

Calling this method on a Player with no arguments disconnects the user from the server and provides a default notice wiadomość. Calling this method on a Player along with a string as the first argument replaces the default message with the provided ciąg.

Kiedy używa się tego metody z LocalScript, tylko lokalny użytkownik może zostać wyrzucony.

Parametry

message: string

Wiadomość do pokazania użytkownikowi po wyrzuceniu.

Wartość domyślna: ""

Zwroty

void

Move

void

Funkcja Przenieś Player powoduje, że postać gracza chodzi w określonym kierunku do końca, lub jest przerwana przez gracza (używając jego elementy sterujące).

Przydatne jest to, gdy skryptuje się NPC Humanoids, który porusza się po mapie - ale nie jest kontrolowany przez rzeczywisty wpis gracza.

Uwaga, że drugi argument funkcji wskazuje, czy dostarczony Vector3 powinien przesuwać gracza względem światowych koordynat ( fałszywy ) lub gracza's Camera ( 1> prawdziwy1> ).

Parametry

walkDirection: Vector3

Kierunek Vector3, w którym powinien poruszać się gracz.

relativeToCamera: bool

Boolean wskazujący, czy gracz powinien poruszać się względem kamery gracza.

Wartość domyślna: false

Zwroty

void

Przykłady kodu

Demonstrates moving a player relative to their camera's position using Player:Move().

The script first waits for the player's Character and Humanoid to load, as both are required before calling Player:Move(). Otherwise a warning will display in the Output.

Moving the Player relative to their Camera

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

void
Zabezpieczenia dodatku plug-in

Funkcja SetAccountAge ustawia Player.AccountAge gracza w dni.

Służy do ustawienia właściwości Player, która opisuje, ile dni temu zostało zarejestrowane konto gracza.

To nie ustawia wieku gracza na konto, ale wieku konta sam w sobie w odniesieniu do czasu jego pierwszego utworzenia.

Parametry

accountAge: number

Wiek konta w dniach.


Zwroty

void

Przykłady kodu

This example demonstrates how the Player:SetAccountAge() function would be used if it was accessible. It sets the local player's account age to 100 days.

Setting the Player's Account Age

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)

This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.

Account Age Mark

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a 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) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
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)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

SetSuperSafeChat

void
Zabezpieczenia dodatku plug-in

Ten metod ustawia, czy gracz widzi czat filtrowany przez TextService:FilterStringAsync() lub zwykłe czaty.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetSuperSafeChat(true)

Niezależnie czy gracz miał włączoną filtrację czatu, cały czat powinien być filtrowany przez TextService przy nadawaniu do innych graczy lub na ekranie gracza. TextService:FilterStringAsync() zwraca obiekt TextFilterResult, który można filtrować w zależności od przeznaczenia wiadomość.

Parametry

value: bool

Boolean wskazujący, czy gracz widzi filtrowany czat.


Zwroty

void

GetFriendsOnline

Wynik

Funkcja ta zwraca arkusz znajomych online, ograniczony przez wartość maxFriends. Funkcja używa 30-sekundowego zapisu.

W zwróconym arkuszu obiektów niektóre pola są tylko dla pewnych typów lokalizacji. Na przykład, PlaceId nie będzie obecny, gdy TypeLocation ma 0 (strona mobilna).


<tbody>
<tr>
<td><b>Id wizytówki</b></td>
<td>liczba</td>
<td>Class.Player.UserId of the znajomy.</td>
</tr>
<tr>
<td><b>Imię użytkownika</b></td>
<td>ciąg</td>
<td>Imię znajomy.</td>
</tr>
<tr>
<td><b>Imię wyświetlanie</b></td>
<td>ciąg</td>
<td>Class.Player.DisplayName znajomy.</td>
</tr>
<tr>
<td><b>LastOnline)</b></td>
<td>ciąg</td>
<td>Kiedy przyjaciel był ostatnio online.</td>
</tr>
<tr>
<td><b>Jest w trybie online</b></td>
<td>boolean</td>
<td>Jeśli przyjaciel jest obecnie online.</td>
</tr>
<tr>
<td><b>Ostatni lokalizacja.</b></td>
<td>ciąg</td>
<td>Imię lokalizacji znajomy.</td>
</tr>
<tr>
<td><b>Identyfikator miejsca</b></td>
<td>liczba</td>
<td>ID miejsca ostatniej lokalizacji znajomy.</td>
</tr>
<tr>
<td><b>Id gry</b></td>
<td>ciąg</td>
<td>Model danych/Id punktu końca znajomy.</td>
</tr>
<tr>
<td><b>Typ lokalizacji</b></td>
<td>liczba</td>
<td>
Typ lokalizacji ostatniej lokalizacji znajomy:
<table>
0 > Strona główna mobilna > 1> Strona główna1> > 4> Strona główna Xbox4> >
<tbody>
7> Strona główna Xbox
</tbody>
7> > 0> Strona główna mobilna0> > 3> Strona główna3> > 6> Strona główna Xbox6> >
<tr>
9> Strona główna mobilna
</tr>
9> > 2> Strona główna2> > 5> Strona główna mobilna5> >
8> Strona główna
8> > 1> Strona główna
</table>
</td>
</tr>
</tbody>
NazwaTypOpis

Parametry

maxFriends: number

Maksymalna liczba przyjaciół online do zwrócenia.

Wartość domyślna: 200

Zwroty

Dizionarium przyjaciół online (zobacz tabelę powyżej).

Przykłady kodu

This example demonstrates how to get a dictionary of a player's online friends. It returns the maximum number of friends specified by the argument, or 200 if an argument is not provided.

Get a List of Online Friends

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

Wynik

Funkcja GetRankInGroup Player zwraca rangę gracza w grupie jako całkowity numer pomiędzy 0 i 255, gdzie 0 jest nieczłonkiem i 255 jest właścicielem grupa.

Używanie tego w Script , a nie w LocalScript, nie dostarczy Ci najnowszych informacji. Jeśli gracz opuści grupę podczas gdy jest w grze, GetRankInGroup nadal będzie myśleć, że jest w tej grupie, dopóki nie opuszczać. Ale to nie dzieje się, gdy używasz lokalnego skryptu.

Dzieje się tak dlatego, że metoda caches wyniki, więc wiele wezwania GetRankInGroup na tym samym graczu z tym samym ID grupy będzie wykonywać taki sam wynik, jak kiedy metoda została po raz pierwszy wezwana z tym samym grupowym ID. Zachowanie kachingowe jest na bazie per-peer: serwer nie dzieli się tą samą kasą jak klient.

Parametry

groupId: number

groupId grupaokreślonej.


Zwroty

Ranga gracza w grupa.

Przykłady kodu

The code below will check if a player that has entered the game has a rank equal to 255, in a group with an ID of 2. If they are, it will print "Player is the owner of the group, 'LOL'!", otherwise "Player is NOT the owner of the group, 'LOL'!" will be printed to the output.

How to Check a Player's Rank in a Group

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

Wynik

Funkcja GetRoleInGroup Player zwraca rolę gracza w grupie jako strungę lub Guest jeśli gracz nie jest częścią grupa.

Używanie tego w Script , a nie w LocalScript, nie dostarczy Ci najnowszych informacji. Jeśli gracz opuści grupę podczas gdy jest w grze, GetRoleInGroup nadal będzie myśleć, że jest w tej grupie, dopóki nie opuszczać. Ale to nie dzieje się, gdy używasz lokalnego skryptu.

Dzieje się tak dlatego, że metoda caches wyniki, więc wiele wezwania GetRoleInGroup na tym samym graczu z tym samym ID grupy będzie wykonywać taki sam wynik, jak kiedy metoda została po raz pierwszy wezwana z danej grupy ID. Zachowanie kachingowe jest na bazie per-peer: serwer nie dzieli się tą samą kasą jak klient.

Parametry

groupId: number

grupowy identyfikator grupaokreślonej.


Zwroty

Rola gracza w określonej grupalub Gość jeśli gracz nie jest członek.

Przykłady kodu

The code below will print the name of the rank that the player is currently a part of, in a specific group. In this instance we're checking what rank the player is within a group which has a group ID of 2.

How to Check a Player's Role in a Group

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

Wynik

Funkcja ta wysyła prośbę do strony Roblox, pytając, czy gracz jest przyjacielem innego użytkownika, biorąc pod uwagę Player.UserId tego użytkownika. Ta funkcja ukrywa wyniki, więc wiele wezwanych funkcji na tym samym graczu z tym samym Player.UserId nie może zwró

Parametry

userId: number

Class.Player.UserId gracza określonego.


Zwroty

Boolean wskazujący, czy gracz jest przyjacielem określonego użytkownika.

Przykłady kodu

The below example would print whether or not a recently added player is friends with Gordonrox24.

How to Check if a Player is a Friend

local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is friends with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

IsInGroup

Wynik

Funkcja IsInGroup Player wysyłuje prośbę o witrynę Roblox, aby zapytać, czy gracz jest członkiem grupa, biorąc pod uwagę ID tej grupa.

Używanie tego w Script , a nie w LocalScript, nie dostarczy Ci najnowszych informacji. Jeśli gracz opuści grupę podczas gdy jest w grze, IsInGroup nadal będzie myśleć, że jest w tej grupie, dopóki nie opuszczać. Jest to jednak nieprawdopodobne, gdy używasz lokalnego skryptu.

Dzieje się tak dlatego, że metoda caches wyniki, więc wiele wezwania IsInGroup na tym samym graczu z tym samym ID grupy będzie wykonywane tego samego wyniku, jak kiedy metoda została po raz pierwszy wezwana z danej grupy ID. Zachowanie kaching jest na bazie per-peer: serwer nie dzieli się tego samego karta pamięci, jak klient.

Parametry

groupId: number

grupowy identyfikator grupaokreślonej.


Zwroty

Boolean wskazujący, czy gracz jest w określonej grupa.

Przykłady kodu

The below example will print "Player is in the Roblox Fan club!" if the newly added player is in the group with a groupId of 7.

How to Check if a Player is in a Group

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

void
Wynik

Funkcja LoadCharacter Player utworza nowego gracza dla gracza, usuwając starego. Usuwa również Backpack i PlayerGui gracza.

Przydatne jest to w przypadkach, gdy chcesz ponownie załadować postać bez zabijania gracza, takich jak gdy chcesz załadować nowy wygląd postaci po zmianie Player.CharacterAppearance gracza.

Uwaga: Funkcja jest podobna do Player:LoadCharacterBlocking() , ale prośba jest przetwarzana asynchronicznie zamiast być przetwarzana szybko. Oznacza to, że inne zadania będą mogły się kontynuować, podczas gdy postać jest ładowana, w tym renderowanie gry i inne zadania. Również, ta funkcja może być używana w skrypcie, podczas gdy LoadCharacterBlocking nie może.

Po wezwaniu LoadCharacter dla jednego gracza, nie zaleca się go ponownie wzywać do tego samego gracza, aż po zakończeniu wydarzenia Player.CharacterAppearanceLoaded tego gracza.

Charakter Loading Event order

Wezwanie Player:LoadCharacter() z użyciem R15 Avatar wyzwala następujące wydarzenia w kolejności (Uwaga: R6 ma inny algorytmu sortowania):

  1. Player.Character ustawia
  2. Dodane pożary gracza
  3. Player.Changed wygrywa z wartością „Character”
  4. Wygląd postaci inicjalizuje
  5. Player.CharacterAppearanceLoaded ogniste
  6. Character.Parent ustawiony na DataModel
  7. Ryglika postaci tworzy się, a postać skaluje się
  8. Znaki poruszają się do lokalizacji spawn
  9. Zwraca postać

Zwroty

void

Przykłady kodu

This script turns off auto-loading and simulates character respawning.

Turn Off Auto-Loading and Simulate Character Respawn

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

void
Wynik

Ta funkcja tworzy awatar, więc ma wszystko założone w przepustkach w HumanoidDescription .

Po wezwaniu LoadCharacterWithHumanoidDescription dla jednego gracza, nie zaleca się ponownie wzywać funkcji dla tego samego gracza, aż po zakończeniu wydarzenia Player.CharacterAppearanceLoaded tego gracza.

Zobacz również:

  • System opisu ludzkiego, artykuł, który wyjaśnia system opisu ludzkiego w większym szczególe i zapewnia kilka przykładów skryptów

Parametry

humanoidDescription: HumanoidDescription

A HumanoidDescription zawierające cechy, takie jak części ciała/kolory, skalowanie ciała, akcesoria, ubraniei animacje, które zostaną założone do załadowanego postaci.


Zwroty

void

Przykłady kodu

To create a HumanoidDescription and then spawn a character with that description applied, add a Script (not a LocalScript) to the workspace and add this code to it.

Spawn Characters With HumanoidDescription

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)

RequestStreamAroundAsync

void
Wynik

Dla doświadczeń, w których włączone jest przesyłanie instancji strream, wnioski, które serwer przesyła do regionów graczy (części i terenu) wokół określonego X , Y ,

Efekt tego wezwania będzie tymczasowy, a nie ma gwarancji, co zostanie przesłane wokół określonego lokalizacji. Ograniczenia pamięci klienta i warunki sieci mogą wpływać na to, co będzie dostępne na klencie.

Ostrze?enie o u?ywaniu

Żądanie przesyłania wokół obszaru nie jest gwarancją , że treść będzie obecna, gdy prośba zostanie zakończona, ponieważ przesyłanie jest wpływane przez sieciową przepustowość, ograniczenia pamięci i inne czynniki.

Parametry

position: Vector3

Lokalizacja na świecie, gdzie wymagana jest transmisja.

timeOut: number

Opcjonalny czas wygasa dla prośba.

Wartość domyślna: 0

Zwroty

void

Zdarzenia

CharacterAdded

Wydarzenie CharacterAdded uruchomione jest, gdy postać gracza pojawia się (lub odzyskuje). To wydarzenie uruchomione jest wkrótce po ustawieniu Player.Character na nieznaną wartość lub wezwaniu Class.Player:LoadCharacter() , co jest przed tym, jak znak znakuje 2>Class.Workspace2>.

Można go używać wraz z wydarzeniem Player.CharacterRemoving, które wstrzyma gracza tuż przed usunięciem gracza, zwykle po śmierci. Jako takie, obie te wydarzenia mogą potencjalnie spalić wiele razy, gdy gracz dołącza lub wychodzi z gry. Jeśli chcesz wykryć

Uwaga, że Humanoid i jego domyślne części ciała (głowa, tułówko i kończyny) będą istnieć, gdy ten incydent się zet

Parametry

character: Model

Instancja postaci, która się pojawiła/odrodziła.


Przykłady kodu

This code sample demonstrates the usage of Players.PlayerAdded, Player.CharacterAdded and Player.CharacterRemoving in order to detect the spawning and despawning of players' characters. You can use this as a boilerplate script to make changes to players' characters as they spawn, such as changing Humanoid.WalkSpeed.

Detecting Player Spawns and Despawns

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)

This code sample will cause players to respawn at the same place they died. It does this by keeping track of where the player despawned using Player.CharacterRemoving. Note that the player's location is saved on-despawn, not on-death. This can be problematic if the player falls off a ledge and dies due to Workspace.FallenPartsDestroyHeight - their respawn position won't be saved in this case.

It's also important to note the need to "forget" the location of players who leave the game. We use Instance.ChildRemoved on Players instead of Players.PlayerRemoving. This is because PlayerRemoving fires before CharacterRemoving - and we need to make sure we don't forget the player's respawn location then immediately remember a new one (this is a memory leak; potentially many players could visit, respawn and leave). So, we use ChildRemoved on Players so the event fires after the character is removed.

Respawn at Despawn Location

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)

This code sample automatically removes Accessory objects like hats from the Player's character when they respawn. Warning: this includes hair, so this script may cause acute baldness.

When the Character() is added, we wait for RunService.Stepped to fire once (using the wait function of events). This is so the accessory removal logic runs one frame after the character spawns. A warning can appear if you delete accessories too quickly after the player spawns, so waiting one frame will avoid that.

Accessory Remover

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)
-- Wait a brief moment before removing accessories to avoid the
-- "Something unexpectedly set ___ parent to NULL" warning
RunService.Stepped:Wait()
-- Check for any existing accessories in the player's character
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Hats may be added to the character a moment after
-- CharacterAdded fires, so we listen for those using ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

CharacterAppearanceLoaded

Ten wążdź się uruchomi, gdy pełen wygląd Player.Character zostanie wstawiony.

A Player.Character ma ogólnie zasięg obiektów modyfikujących jego wygląd, w tym Accoutrements, Shirts, 1> Class.Pants1> i 4> Class.

Jednym z użyć dla tego wydarzenia jest upewnienie się, że wszystkie akcesoria załadowane zanim je usuniesz. Zobacz poniżej przykład tego.

Parametry

character: Model

Class.Player.CharacterModel .


Przykłady kodu

This code sample will wait for accessories to fully load, print out how many there are, and then destroy them all.

Remove Accessories After Loading

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

Wydarzenie CharacterRemoving występuje właśnie przed usunięciem postaci gracza, takie jak gdy gracz się odrodza.

Ten wydarzenie można używać wraz z wydarzeniem Player.CharacterAdded, które jest uruchiwane, gdy postać gracza się pojawia lub odchodzi. Na instancja, jeśli chcesz wydrukować wiadomość za każdym razem, gdy gracz się pojawia i umiera:


local Players = game:GetService("Players")
local function onCharacterSpawned(player)
print(player.Name .. " is spawning")
end
local function onCharacterDespawned(player)
print(player.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function()
onCharacterSpawned(player)
end)
player.CharacterRemoving:Connect(function()
onCharacterDespawned(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

To wydarzenie dotyczy tylko Character Class.Player . Jeśli jednak musisz śledzić, kiedy gracz dołącza/wychodzi z gry, użyj wydarzeń Player i Players.PlayerAdded.

Parametry

character: Model

Instancja postaci, która jest usuwana.


Przykłady kodu

This example prints the name of the character being removed, followed by "has died".

For instance, if Shedletsky's character was to die in-game, "Shedletsky has died." would be printed.

Player.CharacterRemoving

game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)

Chatted

Wydarzenie Chatted włącza się, gdy Player wpisuje wiadomość i naciśnie enter w Roblox's zapewnionym wiadomościach barze. To jest zrobione za pomocą kilku wiązań Lua przez domyślną skryptu czatu. Możesz zapobiec graczom czatu, używając StarterGui:SetCoreGuiEnabled() i wyłączając Chat <

Komendy czatu

Używając tego wydarzenia i kilku funkcji manipulacji strungi, takich jak string.sub() i string.lower(), można tworzyć komendy czatu, nawet z argumentami takimi jak nazwy

Filtrowanie

Tekst wiadomości uruchomiony tym wydarzeniem jest niefiltrowany . Jeśli wyświetlasz wejście gracza jak czat do innych graczy w jakiejkolwiek formie, musi być filtrowane za pomocą Chat:FilterStringAsync() . Pamiętaj o tym, gdy tworzysz własne systemy czatu; jeśli twoja gra nie prawidłowo filtruje czatu, może to być podjęte działanie moder

Parametry

message: string

Treść wiadomości, którą gracz wpisał do czatu.

recipient: Player

Deprecated. Dla wiadomości wącha była to osoba, która była zamierzonym celem wiadomośćw czacie.


Przykłady kodu

Setting chatted for all players. There is an easy way to make the Chatted event registered on all players. Simply use the Players.PlayerAdded event in combination with this event.

Player.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)

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

Playing/Spectating Teams

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)

This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".

Join Team Command

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

Ten ewent wywołuje około 2 minut po tym, jak silnik gry klasyfikuje player jako bezczynność. Czas to liczba sekund, które minęły od tego punktu. Wydarzenie nadal jest uruchamiane co 30 sekund przez cały czas, dopóki gracz pozostaje bezczynność.

Ten wydarzenie tylko zostanie wykonany w skryptach klienta, a nie w skryptach serwera; użyj RemoteEvent , aby poinformować serwer o nieaktywnych graczach.

Roblox automatycznie odłącza graczy, którzy byli nieaktywni przez co najmniej 20 minut, więc ten incydent jest użyteczny do ostrzeżenia graczy, że zostaną odłączeni wkrótce, odłączając graczy przed tymi 20 minutami lub innymi funkcjami dala od klawiatury (AFK).

Aby śledzić, jak często występowaćautomatyczne odłączenie, spróbuj związać to wydarzenie z zdarzeniami Players.PlayerRemoving .

Parametry

time: number

Czas w sekundach, który gracz spędził w bezczynność.


Przykłady kodu

Prints how long a player has been idle for.

Player.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

Wystąpił, gdy zmienił się TeleportState gracza. Ten wątek jest użyteczny do wykrywania, czy teleportacja była udana.

Czym jest TeleportState?

Gdy wysyłany jest żądanie teleportacji za pomocą TeleportService, następuje seria etapów przed teleportacją Player. Obecny etap jest reprezentowany przez wartość Enum.TeleportState, która jest dana przez OnTeleport. Zobacz poniżej dla praktycznego przykładu tego.

Parametry

teleportState: Enum.TeleportState

Nowy Enum.TeleportState``Class.Player .

placeId: number

Identyfikator miejsca, do którego teleportuje się Player .

spawnName: string

Nazwa obszaru pochodzenia do teleportacji, jeśli TeleportService:TeleportToSpawnByName() został użyty.


Przykłady kodu

This example prints which stage of a teleport a player is at, as well as printing if the teleport was a failure.

Player.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)