Whenever I run code, sometimes the object doesn't exist like a characters's Left Leg. How do I check if it's there? Whenever I do:
1 | if character [ "Left Leg" ] ~ = nil then |
2 | --stuf |
3 | end |
it gives me an error. Help?
Use the FindFirstChild method. The FindFirstChild method will search through the children of an object, until it finds an object who's name is the same as the string supplied, then it returns that object. If it doesn't find anything, it returns nil. Example:
1 | if character:FindFirstChild( "Left Leg" ) ~ = nil then |
2 | -- stuff |
3 | emd |
Adding on to 18cwatford's answer, in some cases you may want to wait until the object is created. Use the WaitForChild method.
Example:
1 | local leftLeg = character:WaitForChild( "Left Leg" ) |
If the "Left Leg" object is not added, then the script will wait forever.
Adding on to Merely's answer, WaitForChild only works if an object is added already having a certain name. That is, changing an object's name to the one you are waiting for after setting its parent will not count and your script will still be halted.
This may seem trivial at the moment, but you may come across times when you accidentally set an object's parent and then name it, rendering the WaitForChild method ineffective.
1 | local model = workspace:FindFirstChild( "Model" ) --Find Model |
2 | if not model~ = nil then --Does model exist or not? |
3 | print ( "Oh no! Model doesn't exist!" ) --It doesn't exist! :O |
4 | else --Elseif it does |
5 | print ( "Yay! Model exists!" ) --Yay! It exists! ;D |
6 | end --The end for all the 'if' loop(s) |
To make the code a bit more efficient, you could do
1 | LLeg = Workspace.Player:FindFirstChild( "Left Leg" ) |
2 | if LLeg then |
3 | --Insert Code Here |
4 | end |
Sure you could do all these fancy ~= nil things, but I like to do it like this:
1 | if character [ "Left Leg" ] then -- You don't need to use ~= nil, it checks if you do it like this. |
2 | -- Code |
3 | end |
Well, bye.
Locked by Thewsomeguy and Articulating
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?