- Home /
GetComponentInChıldren does not work
Hello guys;
GameObject myCube = Instantiate(questionPrefab, pos, transform.rotation);
myCube.GetComponent<SpriteRenderer>().material.color = Color.red;
myCube.GetComponentInChildren<SpriteRenderer>().material.color = Color.cyan;
I intantiate a 2D Sprite when i trying to change the color of the children, it actually changes the color of parent.
Whats wrong?
Thanks for your attention.
Answer by ShadyProductions · Jun 15, 2017 at 09:22 AM
Since GetComponentInChildren() searches the parent as well, and returns only the first component it finds, it will return the parent's component. Maybe you want to use GetComponentsInChildren
instead. Then you can loop over all the components.
Thanks. I accept your answer..
How can i get children's Sprite Renderer so, i can change the color of it?
myCube.GetComponent<SpriteRenderer>().material.color = Color.red;
Component[] renderers = myCube.GetComponentsInChildren(typeof(SpriteRenderer));
foreach (SpriteRenderer childRenderer in renderers)
{
childRenderer.material.color = Color.green;
}
It is still all green :( What's the problem
//myCube is the parent
var renderers = myCube.GetComponentsInChildren<SpriteRenderer>();
//children green
foreach (var childRenderer in renderers)
{
childRenderer.material.color = Color.green;
}
//set parent red
myCube.GetComponent<SpriteRenderer>().material.color = Color.red;
Something like this?
Your answer
Follow this Question
Related Questions
Fill Font Characters with White? 0 Answers
Start Application on second monitor 1 Answer
Must I attach every script to a gameobject in order to work ? 2 Answers
Unity 5 Android product name 1 Answer