I have this code that is supposed to find another tool based on its “Referral” name from an attribute. It works fine, but sometimes it doesn’t work as intended.
local function FindTheModel(GunName, tool)
if table.find(GunBehavior.activeguns, tool:GetAttribute("ReferralName")) then -- ensures that the attribute has been noted prior
for _, v in ipairs(NotInPlay:GetChildren()) do
if v:IsA("Model") then
if v:GetAttribute("ToolReferral") == tool:GetAttribute("ReferralName") then
return v -- returns nil and causes an error in the next script
end
end
end
else
return PhysicalDroppedGuns[GunName]:Clone()
end
end
The rest of the code works, but I don’t want to clutter with more errors as I script more of my game and I have no idea how to fix this error.
I assume the case where it returns nil is when the ReferralName attribute of the tool is within the activeguns table but no child of NotInPlay happens to match that attribute. This causes the entire loop to complete without running the return v inside the second if statement, and since you aren’t returning anything under that for loop, it defaults to nil.
This is the reason, now you need to figure out why it happens. One reason I can think of is that the code is running on the client side and the corresponding model hasn’t loaded, or that your code is running too early, for example before the creation of it.
I think it may be due to the instances being transferred from workspace (in folders) to replicatedstorage too fast. But I’m not sure how I can make sure that that code runs first before the other half does