Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Access children of prefab?

Discussion in 'Scripting' started by bigkahuna, Sep 5, 2008.

  1. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Can anyone help with this, I seem to be stuck? I'm instantiating a prefab (an Asset Bundle to be precise) and want to access an element in that prefab by name. The main asset is an empty and children to it are a number of GUI texts. I'm using the attached script to instantiate the Asset Bundle and to test access to the children. The problem is that I want to access each of the GUI Texts individually by their name. How do I do that?

    Code (csharp):
    1. var assetBundle : AssetBundle;
    2. var instanced : GameObject;
    3. var tests;
    4.  
    5. function Start () {
    6.     if (AssetManager.overlayAsset != null) {
    7.         assetBundle = AssetManager.overlayAsset.assetBundle;
    8.         var go : Object = assetBundle.mainAsset;
    9.         instanced = Instantiate(go);
    10.     }
    11.     else {
    12.         print ("No overlay selected!");
    13.     }
    14.     print (go.name + " : " + instanced.name);
    15.  
    16.     tests = instanced.GetComponentsInChildren (GUIText);
    17. }
    18.  
    19. function Update () {
    20. //  This toggles all the GUI Texts on and off: 
    21.     if (Input.GetKey ("up")) {
    22.         for (var text : GUIText in tests) {
    23.             text.enabled = false;
    24.         }      
    25.     }
    26.     else {
    27.         for (var text : GUIText in tests) {
    28.             text.enabled = true;
    29.         }
    30.     }
    31. //  This changes the first GUI Text:   
    32.     if (Input.GetKey ("left")) {
    33.         var test : GUIText = instanced.GetComponentInChildren (GUIText);
    34.         test.text = "WORKS!";
    35.     }
    36. }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    I think transform.Find is what you want?

    --Eric
     
  3. bigkahuna

    bigkahuna

    Joined:
    Apr 30, 2006
    Posts:
    5,434
    Ah Ha! GameObject.Find was it, thanks Eric!!