|
| 1 | +--!strict |
| 2 | + |
| 3 | +local Players = game:GetService("Players") |
| 4 | +local RunService = game:GetService("RunService") |
| 5 | + |
| 6 | +local IS_CLIENT = RunService:IsClient() |
| 7 | + |
| 8 | +type Callback = (character: Model) -> (() -> ())? |
| 9 | + |
| 10 | +--[=[ |
| 11 | + @within Observers |
| 12 | + @client |
| 13 | +
|
| 14 | + Creates an observer that captures the local character in the game. This |
| 15 | + can only be called from client-side code. |
| 16 | +
|
| 17 | + ```lua |
| 18 | + -- In a LocalScript or Client-context script |
| 19 | + observeLocalCharacter(function(character) |
| 20 | + print("Local character spawned") |
| 21 | +
|
| 22 | + return function() |
| 23 | + -- Cleanup |
| 24 | + print("Local character removed") |
| 25 | + end |
| 26 | + end) |
| 27 | + ``` |
| 28 | +]=] |
| 29 | +local function observeLocalCharacter(callback: Callback): () -> () |
| 30 | + assert(IS_CLIENT, "observeLocalCharacter can only be called from the client") |
| 31 | + |
| 32 | + local cleanup: (() -> ())? = nil |
| 33 | + local subscribed = true |
| 34 | + |
| 35 | + local function onCharacterAdded(character: Model) |
| 36 | + local cleanupFn: (() -> ())? = nil |
| 37 | + |
| 38 | + local ancestryChangedConn: RBXScriptConnection |
| 39 | + ancestryChangedConn = character.AncestryChanged:Connect(function(_, parent) |
| 40 | + if parent == nil and ancestryChangedConn.Connected then |
| 41 | + ancestryChangedConn:Disconnect() |
| 42 | + if typeof(cleanupFn) == "function" and subscribed then |
| 43 | + task.spawn(cleanupFn) |
| 44 | + if cleanup == cleanupFn then |
| 45 | + cleanup = nil |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | + end) |
| 50 | + |
| 51 | + cleanupFn = callback(character) |
| 52 | + if typeof(cleanupFn) == "function" then |
| 53 | + if ancestryChangedConn.Connected then |
| 54 | + cleanup = cleanupFn |
| 55 | + else |
| 56 | + task.spawn(cleanupFn) |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + local characterAddedConn = Players.LocalPlayer.CharacterAdded:Connect(onCharacterAdded) |
| 62 | + if Players.LocalPlayer.Character ~= nil then |
| 63 | + task.spawn(onCharacterAdded, Players.LocalPlayer.Character) |
| 64 | + end |
| 65 | + |
| 66 | + return function() |
| 67 | + subscribed = false |
| 68 | + characterAddedConn:Disconnect() |
| 69 | + if typeof(cleanup) == "function" then |
| 70 | + task.spawn(cleanup) |
| 71 | + cleanup = nil |
| 72 | + end |
| 73 | + end |
| 74 | +end |
| 75 | + |
| 76 | +return observeLocalCharacter |
0 commit comments