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

Convert a list of Raycasthit2D to a list of collider2d

Discussion in 'Physics' started by crusty210, Mar 24, 2015.

  1. crusty210

    crusty210

    Joined:
    Jul 29, 2014
    Posts:
    14
    As the title says, what's the most efficient way to covert List<Raycasthit2D> to List<Collider2D> where the collider2D are the corresponding colliders of the Raycasthit2D
     
  2. iSinner

    iSinner

    Joined:
    Dec 5, 2013
    Posts:
    201
    Code (CSharp):
    1. var colliderList = raycastList.Select(rhit=>rhit.collider).ToList();
     
  3. Roni92

    Roni92

    Joined:
    Nov 29, 2013
    Posts:
    225
    You'll also need to use linq namespace to use method which iSinner posted: using System.Linq on top of your script. You can also do it with more "traditional" method, by loop(it doesnt need linq):

    Code (CSharp):
    1. List<Collider2D> collidersList = new List<Collider2D>();
    2. for(int i = 0; i < raycastHitList.Count; i ++){
    3.     collidersList.Add(raycastHitList[i].collider);
    4. }
     
    Last edited: Mar 25, 2015
  4. crusty210

    crusty210

    Joined:
    Jul 29, 2014
    Posts:
    14
    Thanks for the replies guys, I ended up using

    Code (CSharp):
    1. List(T).ConvertAll(TOutput)