How do you set an ObjectValue to nil?

In this code I’m writing, I attempt to set an ObjectValue to nil once a player, the value, dies.

local holder = script:WaitForChild("holder")

holder.Changed:Connect(function()
	if holder.Value ~= nil then
		holder.Value:FindFirstChild("Humanoid").Died:Connect(function()
			holder.Value = nil
		end)
	end
end)

However, it just doesn’t get set to nil. How would I do this?

Theoretically this should work, but can you try printing to see if the event is even firing in the first place?

By the way Changed only fires on the Value property change of ValueBases. This means the new value is passed as argument to your listener.

-- example
local value = Instance.new("StringValue")
value.Changed:Connect(print)
value.Value = "new value!!!"

It is. There’s more in the code that I haven’t mentioned that fires fine, but not the line that sets it to nil

Is there another way for you to obtain reference to the player?

You could try doing it backwards.

Don’t get them from the Value, get them from wherever you set the Value, and then listen for when they die to change the value.

I just tested your code and it does work, it must be an issue elsewhere. Make sure you set holder.Value to the character rather than the player.

1 Like

That to me seems really difficult.

I have a script in my NPCs which runs when they die. Must be the same for players.

So when they die, it executes code.

If the code is then on a player and I want to change the server script, then I will RemoteEvent it.

The server will then change the value to nil.

If it’s an NPC, I will just have the script change the value directly.

So “Hey Server I’m Dead!”

Server “Ok Player1.Value = nil.”

That’s not good practice. You should use the Died event on the server for sure because the client can just never tell the server the player died.

2 Likes

Ahhh… I see. So they can just STOP the code from working and become invincible. Thanks for pointing that out.

Maybe one could put like a serverside variable for that player’s health and check it whenever it changes. If it’s <= 0 then player has died. Server breaks joints. Whenever the value changes send the value by remoteevent to the player and have their health has changed and update the Humanoid.Health with the server value. They can then keep their Humanoid.Health above 0 but the server won’t care what their Humanoid.Health is.

Interesting.

Yep! There’s actually a HealthChanged event for Humanoids which would do exactly that. The client Humanoid definitely can’t control health and the Died event appears to be fired on the server now (it used to be much less reliable) so I’d say that relying on these are probably alright.

To be honest custom health controllers aren’t a bad idea either. They definitely give you more control.

1 Like