This is the relevant snippet of code from my script that errors. When it runs, the second line gives the error: Attempt to index nil with 'FindFirstChild' Any ideas how to fix this? (i’m checking if the character has a tool with a class value of primarygun or secondarygun in it)
local cameraPosition
if char:FindFirstChildWhichIsA("Tool") == true and char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class") == true and char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "PrimaryGun" or char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "SecondaryGun" then
cameraPosition = char:FindFirstChildWhichIsA("Tool").Parts.AimCam.Position
else
cameraPosition = char:WaitForChild("Head").Position + (rightVector * 3) + (upVector * 0.35) + (backvector * -5)
end
This if is incorrect. FindFirstChild (and FindFirstChildWhichIsA) either return nil or the instance named as the parameter you pass (“Tool” as the class name in this case). It does not return true or false. The correct way to execute this if would be
char:FindFirstChildWhichIsA("Tool") ~= nil
Also, you can get rid of certain FindFirstChilds. For example the Class instance, you can avoid re-using it since you’ve checked for its existance earlier
char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class") == true and char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "PrimaryGun" or char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "SecondaryGun"
You can easily turn these into
char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class") and char:FindFirstChildWhichIsA("Tool").Class.Value == "PrimaryGun" or char:FindFirstChildWhichIsA("Tool").Class.Value == "SecondaryGun"
local cameraPosition
if char:FindFirstChildWhichIsA("Tool") then
if char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class") then
if char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "PrimaryGun" or char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class").Value == "SecondaryGun" then
cameraPosition = char:FindFirstChildWhichIsA("Tool").Parts.AimCam.Position
else
print("no primary or secondary gun")
end
else
print("no class")
end
else
cameraPosition = char:WaitForChild("Head").Position + (rightVector * 3) + (upVector * 0.35) + (backvector * -5)
end
Don’t get rid of the first FindFirstChild of course, you still need to verify that the tool exists. Your if statement should look something like this :
if char:FindFirstChildWhichIsA("Tool") and char:FindFirstChildWhichIsA("Tool"):FindFirstChild("Class") and (char:FindFirstChildWhichIsA("Tool").Class.Value == "PrimaryGun" or char:FindFirstChildWhichIsA("Tool").Class.Value == "SecondaryGun") then
-- code
else
-- else code
end