- Home /
Question by
mmyoonsin94 · Mar 17, 2018 at 08:22 AM ·
c#unity 5vuforiarandom.rangestudent
Random get element from a jagged array
//Column
public GameObject[] plastic;
public GameObject[] paper;
int x;
//Row
public GameObject[] sort;
int y;
public GameObject[][] rubbish;
int currentY, currentX;
// Use this for initialization
void Start()
{
plastic = GameObject.FindGameObjectsWithTag("Plastic");
paper = GameObject.FindGameObjectsWithTag("Paper");
sort = GameObject.FindGameObjectsWithTag("Sort");
for (y = 0; y < sort.Length; y++)
{
rubbish = new GameObject[sort.Length][];
for (x = 0; x < plastic.Length || x < paper.Length; x++)
{
rubbish[0] = plastic;
rubbish[1] = paper;
Debug.Log(y + " " + x + " " + rubbish[y][x].name);
//paper.length=3
currentX = Random.Range(0, paper.Length - 1);
//sort.length=2
currentY = Random.Range(0, sort.Length - 1);
Debug.Log("Random rubbish:" + currentY + " " + currentX);
}
}
I have a jagged array with index first row: [0][0], [0][1], [0][2], second row: [1][0], [1][1], [1][2]. Here my code to get random element from the jagged array, and I face some problem: The random element always I get is [0][0] and [0][1], while the other elements are never getting picked. I can't figure out why this happened.
Comment
Best Answer
Answer by hexagonius · Mar 17, 2018 at 09:00 AM
because Range with integers excludes the last number already. putting Length suffices.
I confuse it with the float and int, and I just found it out.
Thank you for your help.