Reputation: 69
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 can't have the same list every time you start a new game
I was thinking if there should be a Random.Range
implemented but I don't know where.
Please Help, and explain what should be done. I'm still a bit new to this and Thanks.
Here's the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
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 ? "" + item.password: " ", 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 int password;
public bool Collected { get; private set; }
public void Collect()
{
Collected = true;
gameObject.SetActive(false);
}
public void passwordNumber()
{
password = 0;
Collected = true;
gameObject.SetActive(false);
}
}
Upvotes: 1
Views: 1585
Reputation: 6169
I assume you'll want to leave items
intact without removing any Items, so I'd suggest creating a second List called finalItems
, which will contain your 5 random Items.
public List<Item> items;
public List<Item> finalItems;
#region Unity
void Start ()
{
Screen.lockCursor = true;
// Do a while loop until finalItems contains 5 Items
while (finalItems.Count < 5) {
Item newItem = items[Random.Range(0, items.Count)];
if (!finalItems.Contains(newItem)) {
finalItems.Add(newItem);
}
}
}
And then in your foreach
statements, loop through finalItems
instead of items
.
This will give you 5 random Items every game!
Upvotes: 1