Reputation: 69
I'm in a little bit of a pickle. I have this script of an array that shows a listing of items. Now the thing is I only want this list to have five items shown out of ten and also shuffled, so you cant have the same list every time you start a new game. I was thinking if there should be a Random.Range implemented but I dont know where. Please Help and Thanks. Heres the script: `
public class RayCasting : MonoBehaviour
{
public float pickupDistance;
public List<Item> items;
#region Unity
void Start ()
{
Screen.lockCursor = true;
}
void Update ()
{
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out hit, pickupDistance))
{
foreach(Item item in items)
{
if(Input.GetMouseButtonDown(0)) {
if (item.gameObject.Equals(hit.collider.gameObject))
{
numItemsCollected++;
item.Collect();
break;
}
}
}
}
}
void OnGUI()
{
GUILayout.BeginArea(new Rect(130,400,100,100));
{
GUILayout.BeginVertical();
{
if (numItemsCollected < items.Count)
{
foreach (Item item in items)
GUILayout.Label(string.Format("[{0}] {1}", item.Collected ? "X" : " ", item.name));
}
else
{
GUILayout.Label("You Win!");
}
}
GUILayout.EndVertical();
}
GUILayout.EndArea();
}
#endregion
#region Private
private int numItemsCollected;
#endregion
}
[System.Serializable]
public class Item
{
public string name;
public GameObject gameObject;
public bool Collected { get; private set; }
public void Collect()
{
Collected = true;
gameObject.SetActive(false);
}
}
`
Upvotes: 0
Views: 18059
Reputation: 11
Just figured it out, this is my solution for shuffle any kind of List
public class Ext : MonoBehaviour
{
public static List<T> Shuffle<T>(List<T> _list)
{
for (int i = 0; i < _list.Count; i++)
{
T temp = _list[i];
int randomIndex = Random.Range(i, _list.Count);
_list[i] = _list[randomIndex];
_list[randomIndex] = temp;
}
return _list;
}
}
With your example it should work like this:
AllItems = Ext.Shuffle<Items>(AllItems);
Debug.Log(AllItems[0]); // Will be always random Item
If you need 5 random Items, you can just call
Debug.Log(AllItems[0]); // Random Item
Debug.Log(AllItems[1]); // Random Item
Debug.Log(AllItems[2]); // Random Item
Debug.Log(AllItems[3]); // Random Item
Debug.Log(AllItems[4]); // Random Item
Upvotes: 0
Reputation: 484
To get a random 5 items from your 10 item list you can use:
List<Items> AllItems = new List<Items>();
List<Items> RandomItems = new List<Items>();
Random random = new Random();
for(int i = 0; i < 5; i++)
{
RandomItems.Add(AllItems[random.Next(0, AllItems.Count + 1)]);
}
The AllItems list contains your 10 items.
After the loop you will have 5 random items inside the RandomItems list.
Upvotes: 1