Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

public Transform[]

Discussion in 'Scripting' started by Fatam0rgana, Oct 17, 2020.

  1. Fatam0rgana

    Fatam0rgana

    Joined:
    Oct 16, 2020
    Posts:
    3
    I declare a public array
    Code (CSharp):
    1. public Transform[] PathElements;
    I need to drag the gameObject from the Hierarche into the PathElements array using code, how can I do that?

    gameObj.jpg arrayPathElements.jpg
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,495
    Code (CSharp):
    1. for (int i = 0; i < PathElements.Length; i++)
    2. {
    3.   PathElements[i] = transform.Find(i.ToString());
    4. }
     
  3. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    A quick tip if you are doing this to save yourself dragging one in at a time.

    If you lock the inspector window (Click the padlock in the top right corner of the inspector tab location) on the object which contains the class with the array, you can then select multiple objects in the hierarchy and drag them into an array or list simultaneously.
     
    VSMGames and adamgolden like this.
  4. Fatam0rgana

    Fatam0rgana

    Joined:
    Oct 16, 2020
    Posts:
    3
    Unfortunately, it didn't help
     
  5. TheOtherUserName

    TheOtherUserName

    Joined:
    May 30, 2020
    Posts:
    136
    Maybe try GameObject.Find(i.ToString()).transform;
     
    adamgolden and Fatam0rgana like this.
  6. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Let me go one step back. Why do you need to do this?
    If you manually create these objects, then you should just manually drag and drop them into the correct location. If you generate these objects somehow, then just add them to that array at the time of their generation.

    Also, be aware that Find() and all of its variations are very slow and generally speaking never have to be used. Absolutely avoid using them inside of Update() or other regularly called functions. If anything, only use them as an initialization inside of Start() or Awake(), and even then they can normally always be avoided. I personally see them as prototyping tools only.
     
  7. Fatam0rgana

    Fatam0rgana

    Joined:
    Oct 16, 2020
    Posts:
    3
    worked!!!! thanks a lot for the help
     
    adamgolden likes this.