Search Unity

Fill array with Child of a GameObject via Script [solved]

Discussion in 'Scripting' started by Andreas12345, Jun 17, 2019.

  1. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    I have in my Scene a Gameobject with childs
    All childs have the name SpawnPoint

    Code (CSharp):
    1.  [SerializeField]
    2.     private Transform[] spawnPoints;
    upload_2019-6-17_14-20-15.png

    How can i add the SpawnPoints via Script?
    I thought it would work with:
    Code (CSharp):
    1.  spawnPoints = transform.Find("SpawnPointers/SpawnPoints")[0];
    But is not right.
     
  2. Kwinten

    Kwinten

    Joined:
    Jan 25, 2015
    Posts:
    49
    Since it's already a serialized array, why can't you just drag the items into the Property field in the inspector? That's what the SerializeField is for :)
     
  3. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    I have more than 1 scene i want to fill in the automatic way
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Transform.Find searches that transform it is called on, not the scene. First, get a reference to the root transform, then search that transform.
    Code (csharp):
    1. GameObject rootGO = GameObject.Find("SpawnPointers");
    2. spawnPoints = new Transform[rootGO.transform.childCount];
    3. for(int i = 0; i < rootGO.transform.childCount; i++)
    4.    spawnPoints[i] = rootGO.transform[i];
     
  5. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    gives me an error

    Code (CSharp):
    1. cannot apply indexing with [] to an expression of type 'Transform'
     
    Last edited: Jun 17, 2019
  6. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Whoops, I think that was some very old syntax or I just misremembered very badly. Replace the last line with
    Code (csharp):
    1. spawnPoints[i] = rootGO.transform.GetChild(i);
     
    Andreas12345 likes this.
  7. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    526
    Great thank you, it works now.

    In the meantime I would have done it by hand, but that was too easy :)