How to use transform.Find()?

Hello,
I have a question:
I wrote this code:

        objectParent = transform.Find("objectName");
          if(objectParent != null)
               {
               if(PlayerPrefs.GetInt(gameObject.name) == 0)
               {
                   objectParent.gameObject.SetActive(true);
               }
               else
               {
                   objectParent.gameObject.SetActive(false);
               }
        }

The object objectName is a child of the object with the script, but every time when I run the script I get this error:
NullReferenceException: Object reference not set to an instance of an object.
Can anyone help pleas? I have no idea wehre the mistake is…
Thank you!

I would avoid the use of transform.Find altogether. It’s fragile and prone to typos.

Why not just have a variable like:

[SerializeField]
Transform myChild;

And simply assign the reference in the inspector?

2 Likes

Thank you, but what is the different between

Transform objectName;

and

[Serializefield]
Transform objectName;

?

https://docs.unity3d.com/ScriptReference/SerializeField.html

It shows up in the inspector so you can drag and drop a game object (in this case its transform component) into it.
Please always read the documentation, it explains most things.

Isn’t that the same like public?

Nope. Other scripts won’t see this property. Which is the purpose of private access.

Ok. Thanks

Juhu! Everything works perfect! Thanks for all of your help!

1 Like