Hello guys.
I have a hierarchy of GameObject in unity like this:
/*Hierarchy
Tile <-- as parent
Enemy <-- as child
note: "Enemy" is an instance of a prefab.
*/
by using this 1st method, I can keep the “Enemy” in a variable (“go”):
// 1st method, working
foreach(transform t in Tile.transform){
if(t.name == ("Enemy")) {
GameObject go = t.gameObject;
<do something with go>
}
}
but if I do as 2nd method:
// 2nd method, not working
GameObject go = Tile.transform.Find("Enemy").gameObject; // always return null;
as I state on the comment, the second method always returning null. I really don’t understand why. I use the 2nd method on the different part of scripts and it works normally.
I did browse similar threads in this forum. I’m sure I’m not making mistake on the gameobject’s name.
He should only have to use the slash if he was targeting Tiles for example. Otherwise, if he’s targeting Tile (8) and looking for it’s children, transform.Find should work.
Personally never had issues with Transform.Find, so I would suspect you have something else going on. Perhaps a timing issue.
I would add some debugs before your second method. Print out Tile.transform.ChildCount for example to see if it even has children at that time. If you have to go deeper, you may need to step through your code.
Thanks for you both. But that’s not the case. Because I used the 2nd method on different time and it works as well. I did check the number of children and it always returns as expected. I will trace my code again.
Transform.Find did not work for me,direct child reference works for me through serializefield, for some reason. I willl consider it stable. I am using latest 2021.3.11f1 LTs version.
Most likely you have the same script on more than one object and one of the other objects (the one you’re not looking at) has no children and is causing the error.