transform.find() weirdly always return null

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.

Is Tile parented to anything?

Hey. Yes it does.
3336407--260325--upload_2017-12-29_21-57-23.png

There is an example of what you have to do in the script reference, basically, start at the uppermost parent and use a directory with a slash.

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.

I understand it worked elsewhere, but that doesn’t mean it’s correct here if it isn’t working. :slight_smile:

Is your Enemy active when you try to Find it?

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.

There’s a reason for this. Transform.Find() is essentially the same Bad Idea™ as GameObject.Find().

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

2 Likes

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.