Choose random instance of object

  • Thread starter WolfgangKampfgarten
  • Start date
W

WolfgangKampfgarten

Guest
Hi everyone,

I have several instances of the same object in my room. How can I randomly choose on of it?

Thanks in advance!
 
W

WolfgangKampfgarten

Guest
Code:
var inst = instance_find(OBJECT, irandom(instance_number(OBJECT) - 1));
After the code is done executing, inst would hold the ID of a random instance of the given object.
Thank you very much, that works!

Does that mean that instances are numbered 1,2,3,...etc. ?
 
R

Randy Becker

Guest
Code:
var inst = instance_find(OBJECT, irandom(instance_number(OBJECT) - 1));
After the code is done executing, inst would hold the ID of a random instance of the given object.
I know this is old, but I cannot find it anywhere else. So I must ask, when I use your code, why does it sometimes randomly choose the top-left corner of my screen? When I use it, I have an object move toward "inst", which works wonderfully. However, there are a few times when it will choose the top-left corner instead and start moving there. Any reason for this?
 
I can only guess you must have an object in the top left corner of the screen.

Are you checking the value you are getting for inst? instance_find() can return the keyword "noone" (which I think internally is the integer number -4 or -2)

You didn't post your code so hard to say.

When you use the code, you could do a show_debug_message("object : " + string(inst) ) to check, or you could use the code:

if ( instance_exists(inst) )
{
// perform move logic here
}
 
V

VojBer

Guest
Can I ask, where is problem in this code? I get error in this code: mp_grid_path(grid,path,x,y,spot_to_go.x,spot_to_go.y,true); ... Thanks

Code:
var spot_taken = false;

var spot_to_go = instance_find (obj_e_spots, irandom (instance_number (obj_e_spots) - 1));

if(!spot_taken){
    stop = path_end();
    grid = mp_grid_create(0,0,room_width/16,room_height/16,16,16);
    path = path_add();
    mp_grid_add_instances(path,obj_object_col,true);
    mp_grid_path(grid,path,x,y,spot_to_go.x,spot_to_go.y,true);
    path_start(path,3,stop,true);
    spot_taken = true;
}
 
Top