- Home /
Get Child from a parent
Hello!!, how to access one of the child of the parents.
I want to access bslider who is child of Item_bbg. Then I will access components of the bslider, as Transform.
Why not putin this item in an public GamObject and access it on start?
Because I'm instantiating the prefabs, and they are different (number of 6 different), but the bslider is the same to every of them. That's why I can't access it by tag or by Finding the name on start.
All I did for now is to create a function that Find all of the childrens and to find the one with the specific name .
public Transform FindChild( Transform parent, string name, SpriteRenderer _energyBarSpriteRenderer)
{
if (parent.name == name)
return parent;
Transform pTransform = parent.GetComponent<Transform> ();
foreach (Transform t in pTransform)
{
if (t.name == name) {
_energyBarSpriteRenderer = t.GetComponent<SpriteRenderer>();
print ("JORA ASTAAA EU!!!");}
}
return null;
}
But then I don't know how to make an object or how to access this children and it's components. I' find him, but how to access it and to use it I don't know (.
Access and use out of the created function.
why not rename them when you Instantiate
then you can search for the names in Awake()/Start()
and get the required components?
when you Instantiate
, you'd do something like this:
private int _numberOfClones = 6;
void Awake()
{
for (var i = 0; i < _numberOfClones; i++)
{
var clone = Instantiate(blah, blah..) as GameObject;
clone.name = "Clone" + i;
}
}
then to find a specific game object, you would
GameObject.Find("Clone1");
Answer by Paulo-Henrique025 · Jul 25, 2014 at 11:27 AM
If the bslider has always the same name you can do:
Transform t = transform.Find("bslider"); // Search only in childs
And then do whatever you want with it.
Answer by SENSBoD · Jul 25, 2014 at 11:33 AM
You can use Find, like in previous post or GetChild to get child by index.
Answer by SilentSin · Jul 25, 2014 at 12:26 PM
I'm not exactly sure what you want, so here are a few possibilities:
Transform bslider = transform.Find("bslider");
Would get you the transform of the child.
SpriteRenderer bsliderSpriteRenderer = GetComponentInChildren<SpriteRenderer();
Would get you the sprite renderer. Though if other children also have sprite renderers, then you shouldn't use this because you don't know which one it will give you.
Also, this line is useless:
Transform pTransform = parent.GetComponent<Transform> ();
"parent" is already a transform, calling GetComponent() on it will just return a copy of the exact same thing. All you would need on the line below is:
foreach (Transform t in parent)
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Display Name Above Object 2 Answers
How to check parent value instead name value(more details in post) 3 Answers
Target child of child without knowing name? 1 Answer
All encompassing Game Object. 1 Answer