Pick Random Object?

Blitz3D Forums/Blitz3D Programming/Pick Random Object?

Trader3564(Posted 2007) [#1]
Can anyone tell me how i pick randomly an object from a type list? I see First, Before, Last, etc.. but no Pick or Random command.


b32(Posted 2007) [#2]
There is no command for that. However, you could write a function for it. You need to know the number of instances the list contains. The best method for that is using functions that wrap both the New and Delete command, so they can keeps count of how many instances are created/destroyed.
;count types
global max=0
For t.MyType = Each MyType
 max=max+1
Next

;get random type
id=0
For t.MyType = Each MyType
 id=id+1
 If id=Rand(Max) then Return t
Next



GfK(Posted 2007) [#3]
;get random type
id=0
For t.MyType = Each MyType
id=id+1
If id=Rand(Max) then Return t
Next
That won't work. Rand will generate a new random number for each iteration, and its possible to get through the entire type collection without success.

Call Rand once, before you loop through your types.