1. Hello Guest! It's with a heavy heart that we must announce the removal of the Legacy GMC Archive. If you wish to save anything from it, now's the time! Please see this topic for more information.
    Dismiss Notice

Choose random instance of object

Discussion in 'Programming' started by WolfgangKampfgarten, Aug 22, 2016.

  1. Hi everyone,

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

    Thanks in advance!
    Josh Chen likes this.
  2. Aura

    Aura Guest

    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.
    Josh Chen, Papa Doge, Gunner and 3 others like this.
  3. Thank you very much, that works!

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

    FrostyCat Member

    Jun 26, 2016
    Not exactly, they are numbered from 0 through instance_number(object)-1.
    Cpaz likes this.
  5. Ok, thanks!
  6. Randy Becker

    Randy Becker Guest

    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?
  7. IndianaBones

    IndianaBones Member

    Jul 5, 2016
    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
  8. VojBer

    VojBer Member

    Aug 8, 2018
    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

    var spot_taken = false;
    var spot_to_go = instance_find (obj_e_spots, irandom (instance_number (obj_e_spots) - 1));
        stop = path_end();
        grid = mp_grid_create(0,0,room_width/16,room_height/16,16,16);
        path = path_add();
        spot_taken = true;

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice