CollectionService
*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.
CollectionService gestisce gruppi (collezioni) di istanze con tag .Le etichette sono set di stringhe applicate alle istanze che si replicano dal server al client.Sono anche serializzati quando vengono salvati i luoghi.
L'uso principale di CollectionService è quello di registrare istanze con tag specifici che puoi utilizzare per estendere il loro comportamento.Se ti trovi ad aggiungere lo stesso script a molte istanze diverse, uno script che utilizza CollectionService potrebbe essere migliore.
Le etichette possono essere aggiunte o rimosse attraverso i metodi di questa classe come AddTag() o RemoveTag() .Possono anche essere gestiti direttamente in Studio attraverso la sezione Tag delle proprietà di un'esempioo attraverso lo strumento Editor di tag incorporato.
Replicazione
Quando le etichette si replicano, tutte le etichette su un'istanza si replicano allo stesso tempo .Pertanto, se imposti un tag su un'istanza dal client, quindi aggiungi/rimuovi un tag diverso sullo stesso istanza dal Server, le etichette locali sull'istanza del client vengono sovrascritte.In StreamingEnabled luoghi, le istanze possono essere scaricate mentre lasciano l'area streaming del client.Se un'istanza del genere rientra nell'area streaming, le proprietà e i tag verranno ri-sincronizzati dal Server.Questo può causare cambiamenti apportati da LocalScripts a essere sovrascritti/rimossi.
Sommario
Proprietà
Metodi
Applica un tag a un Instance .
Restituisce un array di tutti i tag nell'esperienza.
Restituisce un segnale che si attiva quando un tag dato viene aggiunto a un'esempio.
Restituisce un segnale che si attiva quando un tag dato viene rimosso da un'esempio.
Restituisce un array di istanze nel gioco con un tag dato.
Ottiene un array di tutti i tag applicati a una determinata esempio.
Verifica se un'istanza abbia un tag dato.
Rimuove un tag da un'esempio.
Eventi
Si attiva quando viene aggiunto un tag a un'istanza e il tag aggiunto è l'unica occorrenza di quel tag nel Posto.
Si accende quando un tag viene rimosso da un'istanza e il tag rimosso non viene più utilizzato da nessuna parte nel Posto.
Proprietà
Metodi
AddTag
Questo metodo applica un tag a un Instance , non facendo nulla se il tag è già applicato a quell'esempio.L'aggiunta di un tag con successo attiverà un segnale creato da GetInstanceAddedSignal() con il tag specificato.
Avvertimenti
I tag di un'istanza aggiunti sul lato client verranno eliminati se il server aggiunge o rimuove un tag su quell'istanza in seguito perché il server replica tutti i tag insieme e sovrascrive i tag precedenti.
Quando si etichette un'istanza, è comune che alcune risorse vengano utilizzate per dare al tag la sua funzionalità, ad esempio connessioni event o tabelle.Per prevenire perdite di memoria, è una buona idea pulirle (disconnetti, imposta su nil , ecc.) quando non sono più necessarie per un tag.Fai ciò quando chiami RemoveTag() , chiami Instance:Destroy() o in una funzione connessa a un segnale restituito da GetInstanceRemovedSignal() .
Parametri
Restituzioni
GetInstanceAddedSignal
Dato un tag (Stringa), questo metodo restituisce un segnale che si attiva sotto due condizioni:
Il tag viene assegnato a un'istanza all'interno del DataModel utilizzando CollectionService:AddTag() o Instance:AddTag() .
Un'istanza con il tag specificato viene aggiunta come discendente del DataModel, ad esempio impostando Instance.Parent o simili.
Le chiamate successive a questo metodo con lo stesso tag restituiscono lo stesso oggetto di segnale.Considera anche di chiamare GetTagged() per ottenere un elenco di istanze che hanno già un tag (e quindi non attiveranno l'evento se sono già in DataModel ).
Vedi anche GetInstanceRemovedSignal() che restituisce un evento che si attiva in condizioni simili.
Parametri
Il tag da osservare.
Restituzioni
Un evento che si attiva quando aggiungi il tag a un'esempio.
Campioni di codice
This code sample causes any BasePart with the tag Deadly to kill any Humanoid that touches it. It does this using a common pattern with CollectionService to listen for all parts with the tag and make a connection, then disconnect the connection when the tag is removed.
local CollectionService = game:GetService("CollectionService")
local tag = "Deadly"
local function onDeadlyPartTouched(otherPart)
if not otherPart.Parent then
return
end
local humanoid = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
-- Save the connections so they can be disconnected when the tag is removed
local connections = {}
local function onInstanceAdded(object)
-- Confirm that the object with this tag is a BasePart
if object:IsA("BasePart") then
connections[object] = object.Touched:Connect(onDeadlyPartTouched)
end
end
local function onInstanceRemoved(object)
-- If there is a stored connection on this object, disconnect/remove it
if connections[object] then
connections[object]:Disconnect()
connections[object] = nil
end
end
-- Listen for this tag being applied to objects
CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
-- Also detect any objects that already have the tag
for _, object in pairs(CollectionService:GetTagged(tag)) do
onInstanceAdded(object)
end
GetInstanceRemovedSignal
Dato un tag (Stringa), questo metodo restituisce un segnale che si attiva sotto due condizioni:
Il tag viene rimosso da un'istanza all'interno del DataModel utilizzando CollectionService:RemoveTag() o Instance:RemoveTag() .
Un'istanza con il tag specificato viene rimossa come discendente del DataModel, ad esempio disattivando Instance.Parent o simili.
Le chiamate successive a questo metodo con lo stesso tag restituiscono lo stesso oggetto di segnale.Il segnale è utile per pulire le risorse utilizzate da istanze che una volta avevano etichette, come la disconnessione delle connessioni.
Vedi anche GetInstanceAddedSignal() che restituisce un evento che si attiva in condizioni simili.
Parametri
Il tag da osservare.
Restituzioni
Un evento che si attiva quando rimuovi il tag da un'esempio.
Campioni di codice
This code sample causes any BasePart with the tag Deadly to kill any Humanoid that touches it. It does this using a common pattern with CollectionService to listen for all parts with the tag and make a connection, then disconnect the connection when the tag is removed.
local CollectionService = game:GetService("CollectionService")
local tag = "Deadly"
local function onDeadlyPartTouched(otherPart)
if not otherPart.Parent then
return
end
local humanoid = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
-- Save the connections so they can be disconnected when the tag is removed
local connections = {}
local function onInstanceAdded(object)
-- Confirm that the object with this tag is a BasePart
if object:IsA("BasePart") then
connections[object] = object.Touched:Connect(onDeadlyPartTouched)
end
end
local function onInstanceRemoved(object)
-- If there is a stored connection on this object, disconnect/remove it
if connections[object] then
connections[object]:Disconnect()
connections[object] = nil
end
end
-- Listen for this tag being applied to objects
CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
-- Also detect any objects that already have the tag
for _, object in pairs(CollectionService:GetTagged(tag)) do
onInstanceAdded(object)
end
GetTagged
Questo metodo restituisce un array di istanze con un tag dato che sono discendenti del DataModel.Rimuovere un tag utilizzando CollectionService:RemoveTag() o Instance:RemoveTag() garantisce che questo metodo non li restituisca.
Se vuoi rilevare tutte le istanze con un tag, entrambe presentano e futuro, usa questo metodo per iterare sulle istanze mentre crei anche una connessione con un segnale restituito da GetInstanceAddedSignal() .
Questo metodo non garantisce alcun ordine delle istanze restituite.Inoltre, è possibile che le istanze possano avere il tag specificato assegnato a loro ma non essere un discendente del DataModel, ad esempio il loro padre è nil ; questo metodo non restituirà tali istanze.
Parametri
Il tag da cercare.
Restituzioni
Un array di tutte le istanze con il tag.
Campioni di codice
This code sample causes any BasePart with the tag Deadly to kill any Humanoid that touches it. It does this using a common pattern with CollectionService to listen for all parts with the tag and make a connection, then disconnect the connection when the tag is removed.
local CollectionService = game:GetService("CollectionService")
local tag = "Deadly"
local function onDeadlyPartTouched(otherPart)
if not otherPart.Parent then
return
end
local humanoid = otherPart.Parent:FindFirstChildOfClass("Humanoid")
if humanoid then
humanoid.Health = 0
end
end
-- Save the connections so they can be disconnected when the tag is removed
local connections = {}
local function onInstanceAdded(object)
-- Confirm that the object with this tag is a BasePart
if object:IsA("BasePart") then
connections[object] = object.Touched:Connect(onDeadlyPartTouched)
end
end
local function onInstanceRemoved(object)
-- If there is a stored connection on this object, disconnect/remove it
if connections[object] then
connections[object]:Disconnect()
connections[object] = nil
end
end
-- Listen for this tag being applied to objects
CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
-- Also detect any objects that already have the tag
for _, object in pairs(CollectionService:GetTagged(tag)) do
onInstanceAdded(object)
end
GetTags
Dato un Instance, questo metodo restituisce un array di stringhe che sono i tag applicati all'esempio.
Questo metodo è utile quando vuoi fare qualcosa con più etichette di istanza contemporaneamente, ma è inefficiente controllare l'esistenza di un'etichetta singola.Per questo, usa HasTag() per controllare un singolo tag.
Parametri
L'istanza il cui tag deve essere restituito.
Restituzioni
Un array di stringhe che sono i tag applicati all'istanza esempio.
Campioni di codice
This code sample demonstrates adding, removing and querying a tag from an object using CollectionService.
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local object = Workspace.Part
-- Add a tag
CollectionService:AddTag(object, "Deadly")
-- Query for a tag
if CollectionService:HasTag(object, "Deadly") then
print(object:GetFullName() .. " is deadly")
end
-- List tags on an object
local tags = CollectionService:GetTags(object)
print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
-- Remove a tag
CollectionService:RemoveTag(object, "Deadly")
HasTag
Questo metodo restituisce se un dato Instance ha un tag.
Per estensione, qualsiasi tag restituito da una chiamata a GetTags() su un'istanza restituirà true quando viene utilizzato con questo metodo.
Parametri
L'istanza per controllare la presenza di un tag.
Il tag da controllare.
Restituzioni
Se l'istanza ha il tag.
Campioni di codice
This code sample demonstrates adding, removing and querying a tag from an object using CollectionService.
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local object = Workspace.Part
-- Add a tag
CollectionService:AddTag(object, "Deadly")
-- Query for a tag
if CollectionService:HasTag(object, "Deadly") then
print(object:GetFullName() .. " is deadly")
end
-- List tags on an object
local tags = CollectionService:GetTags(object)
print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
-- Remove a tag
CollectionService:RemoveTag(object, "Deadly")
RemoveTag
Questo metodo rimuove un tag da un'esempio. La rimozione di un tag con successo attiverà un segnale creato da GetInstanceRemovedSignal() con il tag specificato.
Quando si rimuove un tag, è comune che alcune risorse vengano utilizzate per dare al tag la sua funzionalità, ad esempio connessioni event o tabelle.Per prevenire perdite di memoria, è una buona idea pulirle (disconnetti, imposta su nil , ecc.) quando non sono più necessarie per un tag.
Parametri
L'istanza per rimuovere il tag da.
Il tag da rimuovere dall'esempio.
Restituzioni
Campioni di codice
This code sample demonstrates adding, removing and querying a tag from an object using CollectionService.
local CollectionService = game:GetService("CollectionService")
local Workspace = game:GetService("Workspace")
local object = Workspace.Part
-- Add a tag
CollectionService:AddTag(object, "Deadly")
-- Query for a tag
if CollectionService:HasTag(object, "Deadly") then
print(object:GetFullName() .. " is deadly")
end
-- List tags on an object
local tags = CollectionService:GetTags(object)
print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
-- Remove a tag
CollectionService:RemoveTag(object, "Deadly")
Eventi
TagAdded
Questo evento si attiva quando viene aggiunto un tag a un'istanza e il tag aggiunto è l'unica occorrenza di quel tag nel Posto.
Parametri
TagRemoved
Questo evento si attiva quando un tag viene rimosso da un'istanza e il tag rimosso non viene più utilizzato da nessuna parte nel Posto.