Edited.
Here’s a much more efficient implementation and probably exactly what you want in terms of “chance”. Since you said your items never change after the Start function is called, I just made an array to represent the range of chance that each item falls into. Using the random number generator, whatever range of chance the randomly generated number falls into, then the item corresponding to the range will be returned. What makes this much more efficient is that I use a binary search compared to a linear search. If you have N items, then this algorithm will take at most log( N ) operations. Using a linear search would take at most N operations. Imagine if you had 1024 items. That’s 1024 operations. But log( 1024 ) is only 10 operations
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Spawner : MonoBehaviour {
public Item[] items;
public Tuple<float,float>[] itemChance;
private BinarySearchComparer binarySearchComparer;
private Transform MyTrans;
void Start ()
{
MyTrans = transform;
float totalChance = 0;
for ( int i = 0; i < items.Length; ++i )
totalChance += items*.spawnChance;*
float beginningOfChance = 0;
float endOfChance = 0;
itemChance = new Tuple<float,float>[items.Length];
for ( int i = 0; i < items.Length; ++i ) {
endOfChance = beginningOfChance + item.spawnChance / totalChance;
itemChance = new Tuple<float,float>(beginningOfChance, endOfChance );
beginningOfChance = endOfChance;
}
binarySearchComparer = new BinarySearchComparer();
StartCoroutine(Spawn());
}
void Update ()
{
}
IEnumerator Spawn()
{
while (true)
{
Vector3 drop = new Vector3 (MyTrans.position.x + Random.Range(GameController.GM.minX + 0.2f,GameController.GM.maxX - 0.2f), MyTrans.position.y,0f);
Instantiate (currentSpawn(),drop,Quaternion.identity);
yield return new WaitForSeconds(Random.Range(0.5f,1.5f));
}
}
private Item currentSpawn()
{
float chance = Random.Range(0, 100);
int index = Array.BinarySearch( itemChance, chance, binarySearchComparer );
return items[index];
}
public class Tuple<T,U>
{
public T Item1 { get; private set; }
public U Item2 { get; private set; }
public Tuple(T item1, U item2)
{
Item1 = item1;
Item2 = item2;
}
}
private class BinarySearchComparer : IComparer<Tuple<float, float>>, IComparer
{
public int Compare( float chance, Tuple<float, float> changeRange)
{
if ( chance <= chanceRange.Item1 )
return -1;
if ( chance > chanceRange.Item2 )
return 1;
return 0;
}
}
}