Reputation: 13
Typical bush of some Zelda with typical reward for destroy it then I have this code to manage it:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
anim.SetTrigger("isTrigger");
this.GetComponent<AudioSource>().PlayOneShot(grassSound);
coll.enabled = false;
//Spawn Items
System.Random rnd = new System.Random();
drop = rnd.Next(1, 31);
if ((drop >= 1) && (drop <= 10))
{
Invoke("InstCoin", 0.2f);
}
else if ((drop >= 27) && (drop <= 30))
{
Invoke("InstHeart", 0.2f);
}
Invoke("HideSprite", 0.8f);
}
}
private void HideSprite()
{
Destroy(gameObject);
}
private void InstCoin()
{
Instantiate(coin).transform.position = gameObject.transform.position;
}
private void InstHeart()
{
Instantiate(heart).transform.position = gameObject.transform.position;
}
But when I hit 2 prefabs (same object) with 1 collider at the same time (because its instant the spawn of that collider of an attack), I generate a random number that make reference to one item (Coin, Heart or nothing).
The issue comes when I get the same item in this cases from both prefabs, I think its because the random function is generating one number (from some internal clock) and then uses the same number on both functions because are "working" at the same time but don't know...
I don't know how to solve this cause both of those prefabs are getting destroy at the same moment.
Tried with saving a float the last number generated and if is the same then reroll the random, but then I'm missing the possibility of get the same number on both prefabs independently, and being at the same time don't know how it works with writing on the same var at the same moment.
Upvotes: 0
Views: 43
Reputation: 291
System.Random rnd = new System.Random();
drop = rnd.Next(1, 31);
This is your issue from what I think you're asking. If the two colliders are hit at the same time then they will both generate the same random number as you're
i think its cause the random funtion is generating one number (from some internal clock)
Correct! They will both be calculating off the same number too. This is a very common issue one runs into when they first start using the Random class :)
To solve it you could generate the random number with a seed. When you instantiate the prefabs you could pass them a unique number to generate their seed off.
Upvotes: 0