You can write your topic however you want, but you need to answer these questions:
- What do you want to achieve? Keep it simple and clear!
I would like to prevent routine errors I get that all fall into a category of “attempt to index nil with…”
- What is the issue? Include screenshots / videos if possible!
I have hundreds of references to player (or NPC) attributes, such as Humanoid, HumanoidRootPart, Head, Torso, etc. And also some folders I have as descendents of the player. Most of the time these references work fine, but occasionally (and too often for a well functioning game) I get an error along the lines of "attempt to index nil with [whatever I am referencing]. I am assuming this is because the player model (or NPC model) is not fully loaded when the lines of code are run - but this is a bit confusing to me because many times the errors occur in the middle of the game.
- What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I’ve tried a number of solutions - many which seem to work but I don’t have strong confidence in the right uniform approach and the approach that can best scale the most efficiently across these hundreds of references. In some cases my solutions check to see if player or character or humanoid or (etc) exist before using it in a line of code. In other cases I prefer to be waiting for the player / character / etc to load before taking action. Here are some of the solutions I am using:
(1) if player and player.Character then… OR other times if humanoid then…
(2) local function onCharacterAdded(character)
local char = character
hrp = char.HumanoidRootPart
– Use char and hrp variables as needed in the rest of the script
end
(3) local function getUniversalModelHumanoidRootPart(instance)
local character = instance.Character
while not character or not character:FindFirstChild(“HumanoidRootPart”) do
character = instance.Character
wait()
end
return character:FindFirstChild(“HumanoidRootPart”)
end
(4) local humanoidRootPart = character:WaitForChild(“HumanoidRootPart”)
(5) local humanoidRootPart = character:FindFirstChild(“HumanoidRootPart”)
(6) local player = game:GetService(“Players”):GetPlayerFromCharacter(playerModel)
local Character = player.Character or player.CharacterAdded:wait();
repeat wait() until Character:FindFirstChild(“HumanoidRootPart”)
I would like to settle on a consistent, repeatable, efficient, performant, and reliable approach for this recurring issue.
After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
-- This is an example Lua code block
Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.