Creating random lists from a multidimensional array

Updated on November 4, 2017 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on November 3, 2017

Hi all,

I have using VS2017 C# and Unity, I have taken Brackeys course: ‘How to program in C#’ and now wanted to play around more with arrays – possibly I’m going in too deep as a beginner, nevertheless, I have taken my time to try and investigate myself and struggling to find a working solution. I was able to create two separate arrays and randomly select 1 element from each array using random.range and store it in a new list, however, as I would like to have multiple arrays in the future I think there must be a better way to go about this.

 

Objective: I would like what I believe is called a multidimensional or jagged array – So the multidimensional array would contain for example 10 first names, 10 second names and 5 ages (this array could grow as I see fit to add information such as height or weight).

I would then like to randomly generate a person by selecting an element from each of the arrays and to store this I guess in a list as I would not know the number of items as it grows.

 

Because noone likes to just be fed answers otherwise you never learn things, I tried myself and below is an example where I got stuck – I hope I was on the right lines:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestScript : MonoBehaviour {
public string[][] listOfPeople = new string[3][];
public List<string> randomGeneratedPeople = new List<string>();
public void Start ()
{
listOfPeople[0] = new[] { "Matthew", "Mark", "Luke", "John" };
listOfPeople[1] = new[] { "Matthewson", "Markson", "Lukeson", "Johnson" };
listOfPeople[2] = new[] { 18, 19, 20 };
//Below was the code I used to generate random from a single array.
//randomGeneratedPeople.Add(listOfPeople[Random.Range(0, listOfPeople.Length)]
}

 

If anyone has any reference material out there on what I want to try and achieve I would much appreciate it.

 

Thank you!

  • Liked by
Reply
0 on November 3, 2017

That’s a bad approach to the problem. You should create a class instead.

  • Liked by
Reply
Cancel
0 on November 4, 2017

As Leon Laci says:

Create a new class as a whole new script for example:

using UnityEngine;
public class People
{
public string firstName;
public string secondName;
public int age;  
public People(string _firstName, string _secondName, int _age)
{      
firstName = _firstName;
secondName = _secondName;
age = _age;
}
}

And then use this as a list as you tried:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TestScript : MonoBehaviour {
public List<People> randomGeneratedPeople = new List<People>();
public void Start ()
{
randomGeneratedPeople .Add(new People("Clark", "Kellog", 38))
}
}
  • Liked by
Reply
Cancel