PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

How to Handle Non-Existent Objects

How to Handle Non-Existent Objects

Jun 23 2018, 2:02 AM PST

Problem

Sometimes when you index objects you get an error like: “Something is not a valid member of Model”. How can this be resolved?

Solution

Use the FindFirstChild method.

local hum = Workspace.Player:FindFirstChild("Humanoid")
if hum then
	hum.Health = 0
end

Discussion

The FindFirstChild method sounds quite cryptic and can be a little daunting at first. When a game is first started up (when the server is loading), all the scripts execute. Meaning that before your in-game character is even spawned, your scripts have already started running. What happens if you have a script where it expects you to be there, but you aren’t? It errors because it cannot find you.

To fix this we use a safe index which as the name implies, safely indexes objects so that it doesn’t error. The first line of the solution will safely index Humanoid within the character. If the Humanoid exists then hum will be set to that Humanoid. Otherwise, hum will be set to nil.

The conditional then checks if hum is not nil (this is how conditionals work in Lua) and if it isn’t, then the Health of the Humanoid will be set to 0. This begs the question, “What if the Player doesn’t exist too, like at the start of the game?”. Very good point. Here is how one would safely index a Humanoid from a character.

local pl = Workspace:FindFirstChild("Player")
if pl then
	local hum = pl:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end

Now this will only run at the start of the game. Since no characters are loaded at the start of the game, this will do nothing, right? Correct. Therefore if you want to kill “Player” once they’ve entered the game, you would do something like this.

repeat wait() until Workspace:FindFirstChild("Player") and Workspace.Player:FindFirstChild("Humanoid")
Workspace.Player.Humanoid.Health = 0

This code uses the wait function (which will be covered in more depth later) in order to wait until the character named “Player” spawns and this character has a Humanoid. Then it sets the humanoid’s health to 0.

This method is useful in a number of contexts in which a race condition exists, or to code defensively against variables you assume to be set, but aren't.
Tags:
  • humanoid
  • model
  • debugging