- Home /
Array only returning first value C#
public Unit[] getUnits()
{
return units;
}
Basically this thing is being stubborn, the reasoning is beyond me. It has 9 values in it that can be accessed with other functions such as
public Unit unit(int num)
{
return units[num];
}
however attempting to return the array for a foreach is met with errors when attempting to manipulate past the first(0) object. The below code will allow the unit to do the animation -- but only the first one.
foreach (Unit u in players[0].army.getUnits())
{
u.anim(ACTION.STRIKE3);
}
It feels like something dumb is being done by me, but I can't for the life of me figure out what it is. The unit Army class is being accessed in the first two functions, trying to get the unit class objects, which calls prefabs.
Answer by EliteMossy · Apr 23, 2013 at 10:59 PM
public Unit[] getUnits() { return units; }
is not really the proper way to do it. You should use properties for something simple like this.
private Unit[] units;
public Unit[] Units{ get { return units; } }
Is a proper way to do it, then
foreach (Unit u in players[0].army.Units)
{
u.anim(ACTION.STRIKE3);
}
I am just assuming this is what you are after. Also check to see what the length of Units is, by doing Debug.Log(players[0].army.Units.Length);
The length is 9, as it should be, but get nullRef on second pass... will try this and see if there are any changes.
You were right about my lacking syntax. I've been doing web development for far too long it seems.
However the problem still persists. Only thing I could think is that the problem lies in the constructor or in the Unit class.
public Army(string pregen)
{
if (pregen == "test")
{
//9 units
units = new Unit[9];
units[0] = new Unit(JOB.SOLDIER);
units[2] = new Unit(JOB.SOLDIER);
units[3] = new Unit(JOB.SOLDIER);
units[4] = new Unit(JOB.ARCHER);
units[5] = new Unit(JOB.ARCHER);
units[6] = new Unit(JOB.THEIF);
units[7] = new Unit(JOB.THEIF);
units[8] = new Unit(JOB.$$anonymous$$AGE);
}
}
Your answer
