Instantiating with a chance.

How can i use chance to instantiate objects from array?

For example :

object 1 has 30% chance to spawn,

object 2 has 50% chance to spawn ,etc.

I know how to spawn objects from array randomly ,but no idea how to use the chance for them as well. Any ideas?

A really ugly and not recommended way is to just put the objects into the array multiple times based on the odds you want. So so if you wanted object 1 to have a 50% chance, object 2 to have a 30% chance, and object 3 to have a 20% chance, you could make a 10 object array and put object 1 in 5 times, object 2 in 3 times, blah blah blah and then just call random on it.

Maybe slightly better is to just get a random number from say… 1-10. And then do an if statement and define your odds there… if randomnum >= 1 and randomnum <= 5 spawn object 1, else if blah blah blah.

Actually that’s probably still not the best way.

I was thinking about that before…There should be a better way to do this.

Give those objects a weight:

Object Wheight Interval
obj1 10 [1,10]
obj2 5 [11,15]
obj3 1 [16,16]

(The intervals need to be computed dynamically for ease of use.)

Then you random between 1 and the maximum, depending on which interval the number is in, thats the object you spawn.