Author Topic: UIGrid add child with index  (Read 2498 times)

ben

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
UIGrid add child with index
« on: August 13, 2014, 05:22:53 AM »
I'm working on a scroll view. I built it similar to the scroll view in the NGUI example scene. I need to add subcells under a cell that is being clicked by the user. So I'm adding children to the grid and passing the index I want  the subcell to appear on (I added get child index method to UIGrid that returns good results). problem is when I try to add another subcell the previous subcell is moved to the end of the grid. As if the index I passed is only temporary. Any idea how to fix this?
  1. UIGrid parentGrid = transform.parent.GetComponent<UIGrid>();
  2. int index = parentGrid.GetChildIndex(transform);
  3. for(int i =0 ;i<msgArray.Count;i++){
  4.                 GameObject cell=NGUITools.AddChild(gameObject,subCellPrefab);
  5.                 parentGrid.AddChild(cell.transform, index);
  6.  
  7.         }
  8.  
I also tested it not in a for loop with same result

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UIGrid add child with index
« Reply #1 on: August 13, 2014, 08:05:11 AM »
Don't use that UIGrid.AddChild method. It doesn't work the way you expect. It simply changes the parent. It won't work properly until Unity 4.6 or so when the feature it relies on will actually function properly.

If you want your children to appear in a specific order, sort them. Set a sorting function and enable sorting.

P.S. You should also update your NGUI, because that function has been commented out a while back.

ben

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
Re: UIGrid add child with index
« Reply #2 on: August 13, 2014, 09:31:57 AM »
Thank you that led me to the right path. :)
I ended up setting the names of the game objects in the grid in a systematical manner and used the built in sort alphabetical enum. calling Reposition() on the grid after I finish adding items.