- Home /
Spawn chance in my spawner.
Hi guys, I'm trying to have my spawner work depending on the spawn chance of the object. I just can't figure out how to influence the pick. Here's my current code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spawner : MonoBehaviour {
public Item[] items;
private Transform MyTrans;
void Start ()
{
MyTrans = transform;
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;
foreach (Item item in items) // retrieve the spawn chance from the item array.
{
chance = item.spawnChance;
}
Item theSpawn = items[Random.Range(0,items.Length)];
return theSpawn;
}
}
Any ideas? I'm just want to have different spawn rates for my objects, higher point awards spawned less frequently than low score.
I have an idea but will items ever change after the Start() function is called?
nope, I just came up with something:
private Item currentSpawn()
{
float random = Random.Range(1f,100f);
Item theSpawn = null;
foreach (Item item in items) // retrieve the spawn chance from the item array.
{
if(item.spawnChance <= random)
{
theSpawn = item;
}
}
if(theSpawn!=null)
{
return theSpawn;
}
}
But I get a "Not all paths return a value" xception.
Answer by kacyesp · Sep 02, 2014 at 06:43 PM
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[i].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[i] = 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;
}
}
}
Wow, thank you very much. It took me a while to comprehend the whole thing but it it works very well. I have to say this is a bit higher level code than my current understanding of C#, but nevertheless good stuff. Again, thanks. It seems smart to use a tuple for this particular case. Wouldn't have worked if my spawn array was a dynamic list or something.
Really nice answer @kacyesp and nice to see a new active user! :D +1 from me
Answer by Scribe · Sep 02, 2014 at 06:42 PM
Hey there, this should work for you:
public Item[] items;
float totalInfluence;
void Start(){
totalInfluence = CalcInfluences(items);
}
void Update(){
Debug.Log(RandomInfluencedIndex(items));
}
float CalcInfluences(Item[] items){
float sum = 0;
foreach(float i in items){
sum += i.spawnChance;
}
return sum;
}
int RandomInfluencedIndex(Item[] items){
float rand = Random.Range(0f, totalInfluence);
float tempSum = 0;
for(int i = 0; i < items.Length; i++){
tempSum += items[i].spawnChance;
if(rand <= tempSum){
return i;
}
}
return items.Length-1;
}
currently it is setup to return the index of the item that was randomly selected, but you could quite easily swap it to just return the actual item!
Scribe
Fascinating. Thanks, I will give it a go once I completely give up on my approach :)
Sure, there are always several ways of doing anything! I just realised it would be very slightly more efficient to $$anonymous$$us the spawnChance from the random number rather than having another sum variable, like so:
int RandomInfluencedIndex(Item[] items){
float rand = Random.Range(0f, totalInfluence);
for(int i = 0; i < items.Length; i++){
if(rand <= items[i].spawnChance){
return i;
}
rand -= items[i].spawnChance;
}
return items.Length-1;
}
Enjoy!
Well, I ended up using kacyesp's code, but I gave your solution a run as well and it worked too. You guys are amazing thank you all ^^
Your answer
Follow this Question
Related Questions
Random.value not working properly? 1 Answer
probability of child Game objects 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Modify mesh problems 1 Answer