- Home /
Random Number Generated within Array
Hi guys I want to generate a random number (0-9), for every item I pick up. One random generated number for one item I pick up. I'm having a problem with it being an array, which I know if I set Random.Range(0,10), it will randomly generate one number for all the items, which I don't want. How can I implement the Random.Range to each item with in the array? Here is the code:
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);
}
}
Comment
Answer by darthtelle · Jul 09, 2014 at 07:38 AM
int[] randomArray = new int[10];
for(int arrayIndex = 0; arrayIndex < randomArray.Length; arrayIndex++)
{
randomArray[arrayIndex] = Random.Range(0, 10);
}
Do you mean like this? Or does the number get generated inside the single Item class??
int randomNumber;
void Awake()
{
randomNumber = Random.Range(0, 10);
}
Answer by kannan21 · Jul 09, 2014 at 07:59 AM
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class Player : MonoBehaviour
{
public List<Item> items;
void Start()
{
foreach(Item item in items)
item.SetRandomNumber();
}
}
[Serializable]
public class Item
{
public int randomNumber;
public void SetRandomNumber()
{
randomNumber = Random.Range (0,9);
}
}
Your answer
Follow this Question
Related Questions
Randomly Select String from Array 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers