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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Don't understand List<GameObject>

Discussion in 'Scripting' started by boylesg, May 22, 2016.

  1. boylesg

    boylesg

    Joined:
    Feb 18, 2016
    Posts:
    275
    privateList<GameObject>m_arrayButtons=newList<GameObject>();

    If I add one element to this then m_arrayButtons.Count is 7......WTF????

    How do I get the number of elements so I can loop through the list?

    There does not seem to be an appropriate data member or function.

    What the hell happens if I try and do this:

    for (int i = 0; i < m_arrayButtons.Count; i++)
    Debug.Log(m_arrayButtons);
     
  2. cblarsen

    cblarsen

    Joined:
    Mar 10, 2007
    Posts:
    266
    There certainly shouldn't be 7 elements in your list, if you only added one. Please show the code where you add one element and write out the count of m_arrayButtons.

    Your second example should probably be:
    Code (CSharp):
    1.  
    2. for ( int i = 0; i < m_arrayButtons.Count; i++)
    3.    Debug.Log(m_arrayButtons[i].name);
    4.  
    You forgot the subscript. So you were trying to write the entire array.Also, as far as I remember, trying to convert a gameobject to a string just gives its type, so you have to use pick something useful about the gameobject to write out, such as the name.
     
  3. boylesg

    boylesg

    Joined:
    Feb 18, 2016
    Posts:
    275
    Never mind cblarsen, I was carrying out an unnecessary step before adding each element to the array and some how it was adding it seven times.

    I eliminated that unnecessary step and .Count contained what I expected it to contain.