Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I use variables in findfirstchild()?

Asked by
Faazo 84
6 years ago
Edited 6 years ago

I need to find the child of workspace whose name is equal to the string stored in the variable. The problem is when I try to use a variable in findfirstchild, it says the variable is a nil value. This is what I tried:

thisbrick = script.Parent

game.Workspace:FindFirstChild(thisbrick).Transparency = 0.5

In the output it says thisbrick is a nil value.

Yes, I know I could just say script.Parent.Transparency = 0.5, but this is just an example as I need to apply this to a much larger script where doing so wouldn't work, and I decided to just write it on it's own to save your time. If there is an easier way to do this without using findfirstchild please let me know. Thanks!

2 answers

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

Hi Faazo,

The problem is that you're using an Instance in :FindFirstChild()'s parameter rather than a string. Try getting the name of the script.Parent and put that in :FindFirstChild(). For example:

local thisbrick = script.Parent;
local brc = workspace:FindFirstChild(thisbrick.Name); -- Also, the cool thing is that :FindFirstChild() has a second optional parameter, which allows you to choose if it should look through the descendants of everything in workspace. So, if it's hidden somewhere, :FindFirstChild() would still find it as long as it's under workspace. 

Well, I hope I helped and have a wonderful day/night.

Thanks,

Best regards,

~~ KingLoneCat

0
How would you do this for an updating number value? narrowricky -14 — 5y
Ad
Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

The problem in your script is that you're trying to use object in FindFirstChild, not a string which you are supposed to. In your case simple fix would be to just add .Name to FindFirstChild argument

So your script would be:

thisbrick = script.Parent

game.Workspace:FindFirstChild(thisbrick.Name).Transparency = 0.5

Also just in case if you were using a local script, it won't execute in workspace so you should use a server script instead.

oops, sorry I was too slow

Answer this question