I am fairly new to c# and scripting in unity. I am trying to create a survival game and all has gone well so far until i was trying to implement a dismantle feature to dismantle items and get a return back of the required items to make the item. I want to randomly amount of items to give back to the player after dismantling hte item. So i went to Random.Range(). And it seems to only ever give me 1x of 1 item and 0 of the others. I tried dismantling 999 items and got the same results each time. My code is probably not the prettiest atm as i just started writing this part.
My Code:
private void On_DismantleClicked() {
var item = InspectedSlot.CurrentItem;
if (item.ItemData.StackSize > 1) {
InspectedSlot.ItemHolder.RemoveFromStack (1);
} else {
InspectedSlot.ItemHolder.SetItem(null);
}
var requiredItems = item.ItemData.Recipe.RequiredItems;
MessageDisplayer.Instance.PushMessage(string.Format("<color=yellow>{0}</color> has been dismantled", item.Name));
m_DismantleAudio.Play2D();
List<string> dismantledItems = new List<string> ();
for(int i = 0;i < requiredItems.Length;i ++) {
var amountToGive = (int)Random.Range(0,requiredItems[i].Amount);
Debug.Log (requiredItems[i].Name + "; You Will Get " + amountToGive);
if (amountToGive > 0) {
dismantledItems.Add (requiredItems [i].Name + ":" + amountToGive);
}
}
string[] dismantleItems = dismantledItems.ToArray ();
if (dismantleItems.Length > 0) {
for (int i = 0; i < dismantleItems.Length; i++) {
string[] theText = dismantleItems [i].Split(':');
string itemName = theText [0];
int itemAmount;
int.TryParse (theText[1], out itemAmount);
//Debug.Log (itemName + " x" + itemAmount);
m_InventoryContainer.TryAddItem (itemName, itemAmount);
MessageDisplayer.Instance.PushMessage (string.Format ("Recieved <color=yellow>" + itemName.ToString () + "</color> x" + itemAmount.ToString(), itemName));
}
}
}
so lets look at an example:
I have an item called “7.62x39 Ammo” and in order to make this item it takes the following components:
Gun Powder x1
Lead Scrap x2
Brass Scrap x1
so in my script it is setup to select a random number that will tell me how many of each item will be given back on dismantle.
(int)Random.Range(0,requiredItems[i].Amount)
yet it seems it sometimes will give me 1x Lead Scrap back but always 0 Gun Powder and 0 Brass Scrap. Am i writing something wrong?