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

Question [SOLVED ]Get child with highest sibling index?

Discussion in '2D' started by TimTam442, Jul 23, 2022.

  1. TimTam442

    TimTam442

    Joined:
    Jan 23, 2021
    Posts:
    3
    So I need to get a reference to a variable number of children with the highest sibling index. I've tried getting the values and putting them into an array but I can't get the highest amounts in that array. Any help?
     
  2. John_Leorid

    John_Leorid

    Joined:
    Nov 5, 2012
    Posts:
    637
    either
    var lastChild = transform.GetChild(transform.childCount - 1)
    or for the array:
    var lastElement = array[array.Length - 1]

    If you are using Unity V2022, you can also write
    var lastElement = array[^1]
    (which is available at C# Version 8, which should be included in V2022 if I am not mistaken).

    Also if you are not concerned about performance, you can use Linq, by writing
    using System.Linq;
    at the top of the file and then using it with
    var lastElement = array.Last();
    .
     
  3. TimTam442

    TimTam442

    Joined:
    Jan 23, 2021
    Posts:
    3
    thanks for the help but i forgot to mention that i am trying to only get active children. i use SlotParent.GetComponentsInChildren<SlotValue>().GetLength(0); is there a way to get this to work with your code?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Iterate from the childCount - 1 down to zero, looking for the first enabled one, then stop.
     
  5. TimTam442

    TimTam442

    Joined:
    Jan 23, 2021
    Posts:
    3
    thanks a lot mate, got it working
     
    Kurt-Dekker likes this.