SocialService

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Assistenza
Non Replicato

SocialService facilita le funzioni sociali che hanno un impatto sulle relazioni create sulla piattaforma Roblox.Il suo uso principale è mostrare prompt di invito e l'elenco telefonico ai giocatori, consentendo loro di inviare richieste di invito ai loro amici attraverso PromptGameInvite() e PromptPhoneBook() rispettivamente.Puoi sfruttare i segnali quando vengono effettuate tali richieste.

Sommario

Metodi

Eventi

Richiami

Proprietà

Metodi

GetPlayersByPartyId

Instances

Restituisce una tabella di tutti gli oggetti attualmente connessi Player che la proprietà Player.PartyId corrisponde alla fornita partyId .Questo metodo si comporta in modo simile a Players:GetPlayers() ma filtra i risultati per includere solo quei giocatori che appartengono alla parte specificata.

Nota che questo servizio non funziona durante il playtest in Roblox Studio; per testare gli aspetti della tua esperienza utilizzandolo, devi pubblicare l'esperienza e giocarci nell'applicazione Roblox.

Parametri

partyId: string
Valore predefinito: ""

Restituzioni

Instances

Un tavolo di oggetti Player di cui la proprietà Player.PartyId corrisponde alla proprietà passata partyId .

Campioni di codice

The following example listens for when a player joins the experience. If the player is part of a party, it uses SocialService:GetPlayersByPartyId() to retrieve all players in the same party who are currently connected to the server. It then outputs the name of each party member.

SocialService:GetPlayersByPartyId()

local SocialService = game:GetService("SocialService")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId ~= "" then
local partyPlayers: { Player } = SocialService:GetPlayersByPartyId(partyId)
for _, partyMember in partyPlayers do
print("Party Member: " .. partyMember.Name)
end
else
warn("Player is not in a party")
end
end)

This code sample demonstrates how to assign players to Teams based on their Player.PartyId using the SocialService:GetPlayersByPartyId() method. When a player joins the experience, the script checks whether they're part of a party. If so, it attempts to assign them to the same team as other party members. If no match is found or the player isn't in a party, they're placed on the team with fewer members to maintain balance.

Team Rebalance with Party Integration

local Teams = game:GetService("Teams")
local Players = game:GetService("Players")
local SocialService = game:GetService("SocialService")
local redTeam = Instance.new("Team")
redTeam.Name = "Red Team"
redTeam.TeamColor = BrickColor.Red()
redTeam.AutoAssignable = false
redTeam.Parent = Teams
local blueTeam = Instance.new("Team")
blueTeam.Name = "Blue Team"
blueTeam.TeamColor = BrickColor.Blue()
blueTeam.AutoAssignable = false
blueTeam.Parent = Teams
local function assignPlayerToTeam(player)
local partyId = player.PartyId
if partyId == "" then
assignBalancedTeam(player)
return
end
local teams = { redTeam, blueTeam }
local matchingTeam = nil
local partyPlayers = SocialService:GetPlayersByPartyId(partyId)
for _, partyPlayer in partyPlayers do
if partyPlayer ~= player and table.find(teams, partyPlayer.Team) then
matchingTeam = partyPlayer.Team
break
end
end
if matchingTeam then
player.Team = matchingTeam
player.TeamColor = matchingTeam.TeamColor
else
assignBalancedTeam(player)
end
end
function assignBalancedTeam(player)
local redCount = #redTeam:GetPlayers()
local blueCount = #blueTeam:GetPlayers()
local chosenTeam = redCount <= blueCount and redTeam or blueTeam
player.Team = chosenTeam
player.TeamColor = chosenTeam.TeamColor
end
local function groupPlayersByParty()
local seenPartyIds = {}
local groupedPlayers = {}
for _, player in Players:GetPlayers() do
if player.PartyId == "" then
table.insert(groupedPlayers, { player })
elseif not table.find(seenPartyIds, player.PartyId) then
table.insert(seenPartyIds, player.PartyId)
local partyPlayers = SocialService:GetPlayersByPartyId(player.PartyId)
table.insert(groupedPlayers, partyPlayers)
end
end
return groupedPlayers
end
-- Call this function to rebalance teams
local function rebalanceTeams()
local groups = groupPlayersByParty()
table.sort(groups, function(a, b)
return #a > #b
end)
for _, player in Players:GetPlayers() do
player.Team = nil
end
for _, group in groups do
local redCount = #redTeam:GetPlayers()
local blueCount = #blueTeam:GetPlayers()
local bestTeam
if redCount <= blueCount then
bestTeam = redTeam
else
bestTeam = blueTeam
end
for _, player in group do
player.Team = bestTeam
player.TeamColor = bestTeam.TeamColor
end
end
for _, player in Players:GetPlayers() do
player:LoadCharacter()
end
end
Players.PlayerAdded:Connect(function(player)
assignPlayerToTeam(player)
player:LoadCharacter()
player:GetPropertyChangedSignal("PartyId"):Connect(function()
if player.PartyId ~= "" then
assignPlayerToTeam(player)
end
end)
end)

HideSelfView

()

Nasconde la vista dell'attore chiamante se stesso. Se questo metodo viene chiamato mentre la vista dell'attore è già nascosta, non fa nulla.


Restituzioni

()

PromptGameInvite

()

PromptGameInvite() mostra un prompt di invito al giocatore locale attraverso il quale possono invitare i loro amici all'esperienza attuale.Prima di chiamare questo metodo, devi usare CanSendGameInviteAsync() per determinare se il giocatore può inviare un invito, poiché questa capacità può variare a seconda della piattaforma o del giocatore.

Vedi Prompt di invito del giocatore per maggiori dettagli sull'implementazione di prompt di invito, personalizzazione di prompt e notifiche e uso dei dati di lancio.

Parametri

player: Instance

Il Player per richiedere con il popup di invito.

Valore predefinito: ""
experienceInviteOptions: Instance

Oggetto opzionale ExperienceInviteOptions per personalizzare la richiesta.

Valore predefinito: "nil"

Restituzioni

()

Campioni di codice

The following code sample uses CanSendGameInviteAsync() to confirm whether the local Player can send an invite. If true, it then prompts the invite using PromptGameInvite().

Sending an Invite

local SocialService = game:GetService("SocialService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Function to check whether the player can send an invite
local function canSendGameInvite(sendingPlayer)
local success, canSend = pcall(function()
return SocialService:CanSendGameInviteAsync(sendingPlayer)
end)
return success and canSend
end
local canInvite = canSendGameInvite(player)
if canInvite then
SocialService:PromptGameInvite(player)
end

PromptPhoneBook

()

Richiede al dato Player con l'elenco telefonico.Se il giocatore sceglie di chiamare qualcuno, l'evento CallInviteStateChanged si attiva.Dovresti usare CanSendCallInviteAsync() prima di chiamare PromptPhoneBook() poiché la capacità di visualizzare l'elenco telefonico può variare a seconda del giocatore.

Se un giocatore non è idoneo ad aprire l'elenco telefonico, viene visualizzato un dialogo di errore.

Vedi Roblox Connect per un esempio di implementazione di questo metodo.

Parametri

player: Instance

Il giocatore per richiedere con l'elenco telefonico.

Valore predefinito: ""
tag: string

Stringa per aiutare a distinguere tra i vari "punti d'ingresso" del libro telefonico o simili.Ad esempio, puoi passare una stringa che definisce quale regione di un'esperienza il personaggio del chiamante si trova attualmente.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

The following code sample, placed within a child LocalScript of a GuiButton, uses CanSendCallInviteAsync() to confirm that the player can make a call. If so, it connects PromptPhoneBook() to the button's Activated event.

SocialService:PromptPhoneBook()

local Players = game:GetService("Players")
local SocialService = game:GetService("SocialService")
local player = Players.LocalPlayer
local button = script.Parent
button.Visible = false
-- Function to check whether the player can send a call invite
local function canSendCallingInvite(sendingPlayer)
local success, canSend = pcall(function()
return SocialService:CanSendCallInviteAsync(sendingPlayer)
end)
return success and canSend
end
local canCall = canSendCallingInvite(player)
if canCall then
button.Visible = true
button.Activated:Connect(function()
SocialService:PromptPhoneBook(player, "")
end)
end

ShowSelfView

()

Mostra la vista dell'attore chiamante in prima persona. Se questo metodo viene chiamato mentre la vista dell'attore è già visibile, non fa nulla.

Parametri

selfViewPosition: Enum.SelfViewPosition

La posizione in cui posizionare la vista autoriale.

Valore predefinito: "LastPosition"

Restituzioni

()

CanSendCallInviteAsync

Resa

Restituisce true se il dato Player può inviare una chiamata di richiamo a un amico.Dovresti sempre utilizzare il risultato di questo metodo prima di chiamare PromptPhoneBook() poiché l'abilità di aprire l'elenco telefonico può variare a seconda del giocatore.

Vedi Roblox Connect per un esempio di implementazione di questo metodo.

Parametri

player: Instance

L'istanza Player del giocatore che potrebbe inviare un invito di chiamata.

Valore predefinito: ""

Restituzioni

Se il giocatore specificato può inviare un invito alla chiamata.

Campioni di codice

The following code sample, placed within a child LocalScript of a GuiButton, uses CanSendCallInviteAsync() to confirm that the player can make a call. If so, it connects PromptPhoneBook() to the button's Activated event.

SocialService:PromptPhoneBook()

local Players = game:GetService("Players")
local SocialService = game:GetService("SocialService")
local player = Players.LocalPlayer
local button = script.Parent
button.Visible = false
-- Function to check whether the player can send a call invite
local function canSendCallingInvite(sendingPlayer)
local success, canSend = pcall(function()
return SocialService:CanSendCallInviteAsync(sendingPlayer)
end)
return success and canSend
end
local canCall = canSendCallingInvite(player)
if canCall then
button.Visible = true
button.Activated:Connect(function()
SocialService:PromptPhoneBook(player, "")
end)
end

CanSendGameInviteAsync

Resa

CanSendGameInviteAsync() restituisce true se il dato Player può invitare altri giocatori all'esperienza attuale.Dovresti sempre utilizzare il risultato di questo metodo prima di chiamare PromptGameInvite() poiché la capacità di invitare i giocatori può variare a seconda della piattaforma o del giocatore.

Vedi Prompt di invito del giocatore per maggiori dettagli sull'implementazione di prompt di invito del giocatore, sulla personalizzazione di prompt e notifiche e sull'utilizzo dei dati di lancio.

Parametri

player: Instance

L'istanza Player del giocatore potenzialmente invia un invito.

Valore predefinito: ""
recipientId: number

Opzionale Player.UserId del potenziale destinatario , utilizzato per verificare se il mittente può invitare quel destinatario specifico.

Valore predefinito: 0

Restituzioni

Se il giocatore specificato può inviare un invito.

Campioni di codice

The following code sample uses CanSendGameInviteAsync() to confirm whether the local Player can send an invite. If true, it then prompts the invite using PromptGameInvite().

Sending an Invite

local SocialService = game:GetService("SocialService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Function to check whether the player can send an invite
local function canSendGameInvite(sendingPlayer)
local success, canSend = pcall(function()
return SocialService:CanSendGameInviteAsync(sendingPlayer)
end)
return success and canSend
end
local canInvite = canSendGameInvite(player)
if canInvite then
SocialService:PromptGameInvite(player)
end

GetEventRsvpStatusAsync

Resa

Restituisce lo stato RSVP del giocatore locale per l'evento dato.Gli eventi devono essere nell'esperienza attuale e non devono essere già iniziati.Se l'evento è già iniziato, questo metodo restituirà un errore.

Nota che puoi usare PromptRsvpToEventAsync() per richiedere al giocatore di modificare lo stato RSVP per l'evento.

Parametri

eventId: string

L'ID evento dell'evento per richiedere al giocatore di modificare lo stato RSVP per.Questo deve essere un ID evento valido che esiste nell'esperienza attuale, rappresentato come una stringa (non un numero).

Valore predefinito: ""

Restituzioni

Restituisce un Enum.RsvpStatus che indica lo stato RSVP attuale del giocatore per l'evento.Se il giocatore non ha risposto all'evento, questo restituirà Enum.RsvpStatus.None .

Campioni di codice

The following example checks if a player is RSVP'd to an event; if not, it gives them the option to RSVP. If the player is already RSVP'd, it gives them the option to cancel their RSVP.

The following Script assumes that RunContext is set to Enum.RunContext.Client and that two sibling ProximityPrompts are in place: one for following the event and one for unfollowing the event. The prompts are enabled or disabled based on the player's RSVP status.

SocialService:PromptRsvpToEventAsync()

local SocialService = game:GetService("SocialService")
local EVENT_ID = "YOUR_EVENT_ID"
local followPrompt : ProximityPrompt = script.Parent.FollowProximityPrompt
local unFollowPrompt : ProximityPrompt = script.Parent.UnfollowProximityPrompt
local function updatePrompt(rsvpStatus : Enum.RsvpStatus)
if rsvpStatus == Enum.RsvpStatus.Going then
unFollowPrompt.Enabled = true
followPrompt.Enabled = false
else
unFollowPrompt.Enabled = false
followPrompt.Enabled = true
end
end
local success, currentRsvpStatus = pcall(function()
return SocialService:GetEventRsvpStatusAsync(EVENT_ID)
end)
if not success then
-- Could not retrieve RSVP status; don't enable either proximity prompt
warn("Failed to get RSVP status:", currentRsvpStatus)
return
end
print("CurrentRsvpStatus:", currentRsvpStatus)
updatePrompt(currentRsvpStatus)
unFollowPrompt.Triggered:Connect(function(player)
local rsvpStatus = SocialService:PromptRsvpToEventAsync(EVENT_ID)
updatePrompt(rsvpStatus)
end)
followPrompt.Triggered:Connect(function(player)
local rsvpStatus = SocialService:PromptRsvpToEventAsync(EVENT_ID)
updatePrompt(rsvpStatus)
end)

GetPartyAsync

Resa

Restituisce un array di dizionari che contiene dati per tutti i membri associati al dato dato partyId .L'array restituito riflette lo stato attuale del party in tutte le istanze attive del server all'interno dell'esperienza e viene ordinato per il tempo in cui ogni membro del party ha accettato l'invito del party.Questo significa che il primo elemento nell'array è il più antico da accettare e l'ultimo è il più recente.

Questo metodo è utile per recuperare informazioni aggiornate su tutti i membri della parte attualmente nell'esperienza e su diversi server, abilitando il comportamento di gruppo coordinato come la teletrasmissione, il matchmaking o la logica di gioco basata sulla parte.

Ogni dizionario nell'array restituito contiene i seguenti campi:


<th>Tipo di valore</th>
<th>Descrizione</th>
</tr>
</thead>
<tbody>
<tr>
<th><code>Id utente</code></th>
<td>numbero</td>
<td>La proprietà <code>Class.Player.UserId</code> del giocatore.</td>
</tr>
<tr>
<th><code>LuogoId</code></th>
<td>numbero</td>
<td>Il <code>Class.DataModel.PlaceId</code> del luogo in cui il membro del gruppo si trova attualmente.</td>
</tr>
<tr>
<th><code>ID Lavoro</code></th>
<td>struttura</td>
<td>Il <code>Class.DataModel.JobId</code> dell'istanza del server in cui l'utente si trova attualmente.</td>
</tr>
<tr>
<th><code>PrivateServerId</code></th>
<td>struttura</td>
<td>Se applicabile, il <code>Class.DataModel.PrivateServerId</code> quando il membro del party è in un server privato o riservato.</td>
</tr>
<tr>
<th><code>Codice di accesso riservato al server</code></th>
<td>struttura</td>
<td>Se applicabile, il codice di accesso per il server riservato in cui l'utente si trova attualmente.Utile per teletrasportare i membri del gruppo l'uno all'altro utilizzando <code>Class.TeleportService:TeleportAsync()</code> .</td>
</tr>
</tbody>
Chiave

Nota che questo servizio non funziona durante il playtest in Roblox Studio; per testare gli aspetti della tua esperienza utilizzandolo, devi pubblicare l'esperienza e giocarci nell'applicazione Roblox.

Parametri

partyId: string
Valore predefinito: ""

Restituzioni

Un array di dizionari che rappresenta i membri del party specificato che sono attualmente nell'esperienza.

Campioni di codice

The following example checks if a player is in a party when they join. If so, it retrieves the latest party data using SocialService:GetPartyAsync() and outputs the details of each party member.

SocialService:GetPartyAsync()

local SocialService = game:GetService("SocialService")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId == "" then
warn("Player is not in a party")
return
end
local success, partyData = pcall(function()
return SocialService:GetPartyAsync(partyId)
end)
if success and partyData then
for _, partyMemberData in partyData do
print(
partyMemberData.UserId,
partyMemberData.PlaceId,
partyMemberData.JobId,
partyMemberData.PrivateServerId,
partyMemberData.ReservedServerAccessCode
)
end
else
warn("Failed to retrieve party data")
end
end)

PromptRsvpToEventAsync

Resa

PromptRsvpToEventAsync() mostra una richiesta al giocatore locale attraverso cui possono cambiare lo stato RSVP all'evento dato.

Gli eventi devono essere nell'esperienza attuale e non devono essere già iniziati. Se l'evento è già iniziato, questo metodo restituirà un errore.

Nota che puoi usare GetEventRsvpStatusAsync() per controllare lo stato RSVP attuale del giocatore prima di chiamare questo metodo.

Parametri

eventId: string

L'ID evento dell'evento per richiedere al giocatore di modificare lo stato RSVP per.Questo deve essere un ID evento valido che esiste nell'esperienza attuale, rappresentato come una stringa (non un numero).

Valore predefinito: ""

Restituzioni

Restituisce un Enum.RsvpStatus indicando lo stato RSVP nuovo del giocatore dopo che la richiesta viene chiusa.Se il giocatore chiude il prompt senza cambiare lo stato RSVP, questo restituirà Enum.RsvpStatus.None o il loro vecchio Enum.RsvpStatus se hanno già selezionato uno stato.

Campioni di codice

The following example checks if a player is RSVP'd to an event; if not, it gives them the option to RSVP. If the player is already RSVP'd, it gives them the option to cancel their RSVP.

The following Script assumes that RunContext is set to Enum.RunContext.Client and that two sibling ProximityPrompts are in place: one for following the event and one for unfollowing the event. The prompts are enabled or disabled based on the player's RSVP status.

SocialService:PromptRsvpToEventAsync()

local SocialService = game:GetService("SocialService")
local EVENT_ID = "YOUR_EVENT_ID"
local followPrompt : ProximityPrompt = script.Parent.FollowProximityPrompt
local unFollowPrompt : ProximityPrompt = script.Parent.UnfollowProximityPrompt
local function updatePrompt(rsvpStatus : Enum.RsvpStatus)
if rsvpStatus == Enum.RsvpStatus.Going then
unFollowPrompt.Enabled = true
followPrompt.Enabled = false
else
unFollowPrompt.Enabled = false
followPrompt.Enabled = true
end
end
local success, currentRsvpStatus = pcall(function()
return SocialService:GetEventRsvpStatusAsync(EVENT_ID)
end)
if not success then
-- Could not retrieve RSVP status; don't enable either proximity prompt
warn("Failed to get RSVP status:", currentRsvpStatus)
return
end
print("CurrentRsvpStatus:", currentRsvpStatus)
updatePrompt(currentRsvpStatus)
unFollowPrompt.Triggered:Connect(function(player)
local rsvpStatus = SocialService:PromptRsvpToEventAsync(EVENT_ID)
updatePrompt(rsvpStatus)
end)
followPrompt.Triggered:Connect(function(player)
local rsvpStatus = SocialService:PromptRsvpToEventAsync(EVENT_ID)
updatePrompt(rsvpStatus)
end)

Eventi

CallInviteStateChanged

Questo evento si attiva quando lo stato dell'invito di una chiamata di un giocatore cambia.

Parametri

player: Instance

L'istanza Player del giocatore che aveva uno stato di invito di chiamata modifica.

inviteState: Enum.InviteState

Lo stato di invito della nuova chiamata.


Campioni di codice

SocialService.CallInviteStateChanged

local SocialService = game:GetService("SocialService")
local button = script.Parent
local isPhonebookOpen = false
SocialService.CallInviteStateChanged:Connect(function(_, inviteState)
local isCalling = inviteState == Enum.InviteState.Placed
if isCalling or isPhonebookOpen then
button.Visible = false
else
button.Visible = true
end
end)

GameInvitePromptClosed

Questo evento si attiva quando un giocatore chiude una richiesta di invito.

Parametri

player: Instance

L'istanza Player del giocatore che ha chiuso il prompt.

recipientIds: Array

Non più popolata; un array vuoto.


PhoneBookPromptClosed

Si accende quando un giocatore chiude la richiesta dell'elenco telefonico.

Parametri

player: Instance

L'istanza Player del giocatore che ha chiuso il libro telefonico.


Richiami

OnCallInviteInvoked

Un callback per elaborare quando una chiamata viene effettuata dal libro telefonico.Il parametro tag può essere utilizzato per differenziare tra diversi "punti di ingresso" o simili, come descritto in PromptPhoneBook() .Solo un callback può essere impostato.

Parametri

tag: string

Stringa per aiutare a distinguere tra i vari punti d'ingresso del libro telefonico.

callParticipantIds: Array

Array che contiene tutti i giocatori coinvolti nella chiamata. Il chiamante sarà sempre il primo giocatore nell'array.


Restituzioni

Tabella che include le chiavi PlaceId e ReservedServerAccessCode i cui valori sono rispettivamente i DataModel.PlaceId e il codice di accesso al server restituito da TeleportService:ReserveServer(), rispettivamente.

Campioni di codice

SocialService.OnCallInviteInvoked

local SocialService = game:GetService("SocialService")
local TeleportService = game:GetService("TeleportService")
SocialService.OnCallInviteInvoked = function()
local placeId = 0123456789 -- This is the place ID of the desired place to drop call participants into
local accessCode = TeleportService:ReserveServer(placeId)
return { ReservedServerAccessCode = accessCode, PlaceId = placeId }
end