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

Making functions for any kind of class

Discussion in 'Scripting' started by pantang, Mar 1, 2021.

  1. pantang

    pantang

    Joined:
    Sep 1, 2016
    Posts:
    217
    I import a lot of stuff at runtime and have to run some checks but its all with different classes, how could you make this function work with any array handed to it, all variables handed to it will always be the same but the data could change Audio, Strings, Ints etc

    Any tips?

    Code (CSharp):
    1.     private Object[] CheckMerge(bool replace, Object[] defaultData, Object[] newData)
    2.     {
    3.        
    4.         Object[] outputData = defaultData;
    5.         if (newData.Length > 0)
    6.         {
    7.             if (replace) outputData = newData;
    8.             else outputData = outputData.Concat(newData).ToArray();
    9.         }
    10.         return outputData;
    11.     }
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I'm not big on that stuff, but I think either a generic <T> or an interface.
     
    pantang likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,375
    Use generics:
    Code (csharp):
    1.  
    2. private T[] CheckMerge<T>(bool replace, T[] defaultData, T[] newData)
    3. {
    4.     var outputData = defaultData;
    5.     if(newData.Length > 0)
    6.     {
    7.         outputData = replace ? newData : outputData.Concat(newData).ToArray();
    8.     }
    9.     return outputData;
    10. }
    11.  
    What I don't understand is what is the point of this code? It replaces or concats an array, if and only if the new array has data in it... yet it's called 'CheckMerge'???
     
    pantang and SparrowGS like this.
  4. pantang

    pantang

    Joined:
    Sep 1, 2016
    Posts:
    217
    neatness mainly otherwise I need to repeat this 10+ times instead of just having a line.

    its for importing mods, it decides if I am adding or replacing mods and then give me either the default data back or the data with the mods if the pack containted any... and thank you! Generics is what I was looking for