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. Dismiss Notice

Question How to make a single function to manipulate multiple types of list?

Discussion in 'Scripting' started by DCTShinobi, Feb 14, 2023.

  1. DCTShinobi

    DCTShinobi

    Joined:
    Jun 23, 2014
    Posts:
    51
    Hello! I have multiple lists of different types, but I need to do the same thing to them. But I don't know how/if there is a way to make a single function work with different types of lists.

    Basically, I want to "sort" the lists in a random fashion. So I have code that randomizes the list. It works, but I was hoping to simplify and minimize my script by making a single function handle all of the lists instead of reusing the same code for each list. However, when I try to create the function, it won't let me use the same function for the different types of lists.

    So how could I write a function to accept all of these different types?
    Code (CSharp):
    1. List<A> listA
    2. List<B> listB
    3. List<C> listC
    4.  
    5. void DoSomething ()
    6. {
    7.      RandomizeList(listA);
    8.      RandomizeList(listB);
    9.      RandomizeList(listC);
    10. }
    11.  
    12. void RandomizeList (List<?> list)
    13. {
    14.      // Randomize order of list contents
    15. }
    Is there a way to do that? Thank you! :)
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,895
    You can just make the method generic, most likely.

    Like so:
    Code (CSharp):
    1. private void RandomiseList<T>(List<T> collection)
    2. {
    3. }
     
    DCTShinobi and Anthiese like this.
  3. DCTShinobi

    DCTShinobi

    Joined:
    Jun 23, 2014
    Posts:
    51
    Thank you so much! Exactly what I needed! :-D
     
    spiney199 likes this.