Search Unity

array comprehension

Discussion in 'Scripting' started by miseajour34, Aug 11, 2019.

  1. miseajour34

    miseajour34

    Joined:
    Nov 20, 2017
    Posts:
    4
    Hello everybody,

    I follow a youtube tutorial. My code works fine but I don't understand very well what I've wrote. Can you help me please ?

    public static Transform[] points;

    // Start is called before the first frame update
    void Awake()
    {
    points = new Transform[transform.childCount];


    My problem is just on transform.childCount. transform is very abstract for me
     
  2. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    994
    Transform is the component Unity uses to handle position/rotation/scale.

    transform without a capital T, when used in a monobehaviour script, refers to the transform component attached to the gameobject on which the script is on.

    childCount refers to the amount of children a transform has at a given moment. Say you have a GameObject called CardDeck and the GameObject has 4 children GameObjects. If you were to call transform.childCount in a script on the CardDeck object, it would return the number 4.

    As for arrays, imagine you are creating a leaderboard for a game. Every player has a picture and the leaderboard shows the top 100 players. It would be pretty painful to have something like
    Code (CSharp):
    1. Sprite picture1;
    2. Sprite picture2;
    3. Sprite picture3;
    4. Sprite picture4;
    5. // ...
    6.  
    And then be forced to define them this way
    Code (CSharp):
    1. picture1 = Leaderboard.GetPicture(1);
    2. picture2 = Leaderboard.GetPicture(2);
    3. picture3 = Leaderboard.GetPicture(3);
    4. // ...
    In this case, you'd use an array which would allow you to do this
    Code (CSharp):
    1. Sprite[] pictures = new Sprite[100];
    And then you'd be able to define them this way
    Code (CSharp):
    1. for (int i = 0; i < 100; i++)
    2. {
    3.         pictures[i] = Leaderboard.GetPicture(i);
    4. }
    Simply picture an array like a box that can contain several element of the same type. When you are creating an array of Transforms, just imagine you're creating a box to store transforms, rather than creating a transform.

    As for
    Code (CSharp):
    1. points = new Transform[transform.childCount];
    You are essentially saying : points is a new box of transforms and the box is the size of "transform.childCount", which if you remember, is the amount of children GameObjects the current GameObject contains.
     
    SparrowGS likes this.
  3. miseajour34

    miseajour34

    Joined:
    Nov 20, 2017
    Posts:
    4
    thank you so much Antoine, very clear for me now :)
     
    ADNCG likes this.