I have created a prefab. In Unity Scene editor, I dragged the prefab into the scene and named it PrefabA (this is a GameObject instance of the Prefab).

Now, I need to update the PrefabA position.
How can I access the GameObject "PrefabA" during runtime via script?

GameObject prefab =  GameObject.Find("Canvas/PrefabA").GetComponent<GameObject>();

The code above throws Object reference not set to an instance of an object.

  • 2
    \$\begingroup\$ Your question is extremely unclear. Do you want to get the Prefab, or do you want to get PrefabA; and do you understand the difference? \$\endgroup\$ – Zee May 20 '15 at 15:08

Now that I see your problem, this has absolutely nothing in relation to Prefabs, your error resides in addressing the object you're looking for:


Try doing this :

GameObject prefab =  GameObject.Find("Canvas").transform.Find("PrefabA").gameObject;

or this :

 GameObject prefab =  GameObject.Find("Canvas/PrefabA").gameObject;

Tip : You don't need to use GetComponent<GameObject>();, using gameObject is just as correct. Cheers!

  • 1
    \$\begingroup\$ According to the docs on GameObject.Find: "If name contains a '/' character it will traverse the hierarchy like a path name. This function only returns active gameobjects." docs.unity3d.com/ScriptReference/GameObject.Find.html I haven't used it this way, but according to the documentation is should be a valid way to address the gameobject. \$\endgroup\$ – DMGregory May 20 '15 at 15:25
  • \$\begingroup\$ @DMGregory It's the first time I read this. But it seems you're right. \$\endgroup\$ – Zee May 20 '15 at 15:29
  • \$\begingroup\$ @Zee the code snippet provided is working now, thx. \$\endgroup\$ – WenHao May 20 '15 at 15:54
  • 2
    \$\begingroup\$ An alternative that I personally use is a class that keeps record of gameobjects that have been instantiated within the game (within reason, no need to keep record of bullets, except for pooling). It can use the name as a key, or search with partials as long as other criteria is provided to only return a single result. \$\endgroup\$ – Douglas Gaskell May 20 '15 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.