Question by
Hother · Dec 25, 2019 at 11:31 AM ·
findparent-childparent transform
How to find a grandparent without using root
I want to find a transform called canvas, but that is not child of the root, so I can't just use root.Find("Canvas"), cause that seems to find only the childrens.
Also want to do this automaticaly, so the scripts can pick the first canvas name when searching through all the parents. The script will be shared with a lot of game objects.
I found a solution for this but it just look too messy and it just search for 7 "generations". I have to add more line of if's if I need to search the canvas for more generations.
Is there a way to find a transform by name, searching through every parents of a game object?
Or even put theses if's in a for loop?
Here is the script
if (currentScreen == null)
{
currentScreen = this.transform.parent.Find("Canvas");
if (currentScreen == null){
currentScreen = this.transform.parent.parent.Find("Canvas");}
if (currentScreen == null){
currentScreen = this.transform.parent.parent.parent.Find("Canvas");}
if (currentScreen == null){
currentScreen = this.transform.parent.parent.parent.parent.Find("Canvas");}
if (currentScreen == null){
currentScreen = this.transform.parent.parent.parent.parent.parent.Find("Canvas");}
if (currentScreen == null){
currentScreen = this.transform.parent.parent.parent.parent.parent.parent.Find("Canvas");}
if (currentScreen == null){
currentScreen = this.transform.parent.parent.parent.parent.parent.parent.parent.Find("Canvas");}
}
}
Comment