I have many arrays, which have almost the same names, but just different numbers. Can I pass all of them to the function like in my example in the cicle? Or I can only write 9 different function calls?
public GameObject[] ladderGroup0;
public GameObject[] ladderGroup1;
public GameObject[] ladderGroup2;
public GameObject[] ladderGroup3;
public GameObject[] ladderGroup4;
public GameObject[] ladderGroup5;
public GameObject[] ladderGroup6;
public GameObject[] ladderGroup7;
public GameObject[] ladderGroup8;
void Update()
{
//..
for (int i = 0; i < 9; i++ )
IncreaseLadderGroupSize("ladderGroup" + i); //!!!
//..
}
void IncreaseLadderGroupSize(GameObject[] ladderGroupArray)
{
//..
}
Sadly, there is no Macro preprocessor in C#. Could have used macros to achieve this.
But you could try defining the ‘ladderGroup’ as a two dimensional array and just pass the respective 1D array you want using ‘ladderGroup*’, where ‘i’ is the index of the 1D array u want to send.*
Not really much the way you want to do it (with a string), but you can pass each of your fields to the function through a loop with help of Reflection. Yet you should avoid it if this is not for an Editor class since it will affect performances of your game.
using System.Reflection;
// [...]
System.Type type = this.GetType();
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
IncreaseLadderGroupSize(field.GetValue(this));
As, sumeetkhobare mentionned it, you can use an array or a list too.
Problem they require workaround to show in inspector and I guess you populate your arrays via the the slots
2 / The array of objects that contain an array:
public class Test : MonoBehaviour {
public Item [] array;
void Start () {
}
[System.Serializable]
public class Item { public GameObject[] array;}
void IncreaseLadderGroupSize(Item[] ladderGroupArray) { }
}
3 / If you have different array sizes, use jagged arrays:
public GameObject [] [] array = new GameObject[10][];
void Start(){
array[0] = new GameObject;
// and so on
}
void IncreaseLadderGroupSize(GameObject [] [] ladderGroupArray) { }
Memory friendly but do not show in inspector and is a bit of a pain to set and use.
4 / Last but not least, the dictionary:
Dictionary <string , GameObject[]> dict = new Dictionary<string, GameObject[]>();
public GameObject[] ladderGroup0;
public GameObject[] ladderGroup1;
public GameObject[] ladderGroup2;
public GameObject[] ladderGroup3;
public GameObject[] ladderGroup4;
public GameObject[] ladderGroup5;
public GameObject[] ladderGroup6;
public GameObject[] ladderGroup7;
public GameObject[] ladderGroup8;
dict.Add("ladderGroup1", ladderGroup1);
// and so on
void IncreaseLadderGroupSize(Dictionary<string, GameObject[]>dict){}