How to reference new character after old character's death

I currently have this kind of code in my game as a local script parented to PlayerScripts

local Players_Service = game:GetService("Players")

local Player = Players_Service.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Head = Character:WaitForChild("Head")
local InHead = Head:WaitForChild("InHead")

local function MyFunction()
    InHead.Value = "something else"
end

But whenever the initial character dies, the new character won’t be referenced and I can’t figure out a way to do so. I tried doing this:

local function MyFunction()
    local Character = Player.Character
end

and the function is called every time the character is needed, so this was one way to solve my issue, however it seemed very disgusting to do this as I don’t like setting variables to the same thing every second or so, so I scrapped that.

What I came up not so long ago was to disconnect the connection that calls the function and from there, I wasn’t quite sure what to do next. Any help is apprecieated :slight_smile:

tl;dr
I’m trying to reference a player’s new character after the initial character dies, however I can’t figure out a way to do so.

Edit:
Another method that I tried was to parent the script to starter character scripts so that the script would reset every time the character dies, however I need to parent the script to player scripts for several reasons such as organisation and utilisation.

2 Likes
local Players_Service = game:GetService("Players")

local Player = Players_Service.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Head = Character:WaitForChild("Head")
local InHead = Head:WaitForChild("InHead")

Player.CharacterAdded:Connect(function(Char)
    Character = Char
    Head = Character:WaitForChild("Head")
    InHead = Head:WaitForChild("InHead")
end)

local function MyFunction()
    InHead.Value = "something else"
end

Try using this. It’d update the character variable once a new character is added.

EDIT: If this helps, I’d appreciate it if I got marked as a solution :slight_smile:

3 Likes

Alternatively, don’t hold a strong reference to the character. Include a variable for a character in functions that need it, or create a callback that returns Player.Character. I think that’s much simpler.

local function GetCharacter()
    return Player.Character
end
2 Likes