- Home /
Function Parameter, array / random type
I have these two functions
function AddTransform ( transformArray : Transform[], inputTransform : Transform )
{
//save
var tempArray : Transform[];
tempArray = transformArray;
//expand
transformArray = new Transform[tempArray.length + 1];
//copy
for( var i : int = 0; i < tempArray.length; i++ )
{
transformArray[i] = tempArray[i];
}
//add
transformArray[tempArray.length] = inputTransform;
}
function AddFloat ( floatArray : float[], inputFloat : float )
{
//save
var tempArray : float[];
tempArray = floatArray;
//expand
floatArray = new float[tempArray.length + 1];
//copy
for( var i : int = 0; i < tempArray.length; i++ )
{
floatArray[i] = tempArray[i];
}
//add
floatArray[tempArray.length] = inputFloat;
}
Obviously the two are very similar. How could I write one function to accept both floats and transforms?
You know you should be using List.<float> and List.<Transform> right? You can add and remove things from them in a much more efficient way than you are doing in that code. Check out this Unity Gems article which has a section on the use of lists and dictionaries.
Answer by whydoidoit · Dec 08, 2012 at 08:27 AM
You would need to use C# to write a function like that using a thing known as "Generics". Generics are usable in Unity Script (see my comment above) but you can only write the functions in C#. So you should use the built in List.<> which create fully changeable collections that are pretty smart about their memory allocation strategy.