Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

if statement is not working properly?

	if Weapon.LocalScript ~= nil then
		local WeaponLocalScript = Weapon.LocalScript
		local WeaponLocalScriptClone = WeaponLocalScript:Clone()
		WeaponLocalScriptClone.Parent = Weapon
	end

The above code is an if statement from a part in my game. It should check if "Weapon" has a local script, and if it does, then clone it. However, when I test it without a local script in Weapon, I get the error: LocalScript is not a valid member of Tool. This doesn't make sense to me because if the local script is not in the Tool, which it isn't, it should skip over the if statement and continue with the rest of the script. But it doesn't for some reason.

I know I have done if xxx ~= nil statements in other scripts, so I don't understand why this one isn't working.

Thanks.

2 comments

0

try using Weapon:FindFirstChild("LocalScript") instead

0

Find first child was the key. I completely missed it in my trouble shooting. Thanks :)

1 answer

✓ Accepted answer

###This is because you're directly indexing a LocalScript, this is why the script threw an error. You'll need to use the Instance:FindFirstChild() method, for safe indexing.

if Weapon:FindFirstChild("LocalScript") then -- the ~= nil wouldn't be needed
    local WeaponLocalScript = Weapon.LocalScript 
    local WeaponLocalScriptClone = WeaponLocalScript:Clone()
    WeaponLocalScriptClone.Parent = Weapon
end

1 comment

0

Thank you so much for answering. I never would have caught that little mistake. Now I get what FindFirstChild is for.

This discussion is preserved as it was. New answers, comments, and votes are closed.