Attempt to index nil with "FindFirstChildOfClass" ingame but not in Studio

This is a strange one. While testing in Studio, everything seems to be working fine, but when I join the game, a specific system does not work as intended and I get an “Attempt to index nil” error in the ingame console.


The strange part is that the system works flawlessly in Studio, yet ingame, it does not. I also had someone else test the game before and they have claimed that the problem was inconsistent; sometimes it would happen, sometimes it wouldn’t.
Here is the part of the LocalScript’s code that seems to be failing:

local players = game:GetService("Players")
local runservice = game:GetService("RunService")
local storage = game:GetService("ReplicatedStorage")

local player = players.LocalPlayer
local debounce = true

player.CharacterAdded:Connect(function(char)
	
	local animator = char:FindFirstChildOfClass("Humanoid"):FindFirstChildOfClass("Animator")
	local mouse = player:GetMouse()
	local gui = player.PlayerGui:WaitForChild("Target")
	local gui2 = player.PlayerGui:WaitForChild("BotAction")

I would like to know what is causing this code to fail. Again, it works perfectly in Studio testing, just not ingame.

My first guess is that sometimes either the humanoid or animator isn’t loading in before the script goes to find it. From what I’ve read about the CharacterAdded event, that event fires “before the character is parented to Workspace”. I’m not entirely certain on why, but I find that objects that aren’t parented to something tend to have some unexpected behavior. As such, I’d suggest adding WaitForChild methods to the humanoid as well.

1 Like

Alright. I’ll use WaitForChild() for the Humanoid and see how it goes. Thank you.

I don’t seem to be getting the problem anymore. I’ll return in case it occurs again, but for now, it seems to have solved the issue. I think it’s quite strange that this issue can happen through the CharacterAdded event.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.