Numbering Instances based on their position

L

Liam_Ihasz

Guest
I have an object which I have placed 10 of in a room, in a line going left to right. I need to be able to number each object (1 - 10) going from left to right and then store that in a variable (ObjId). I am not 100% sure how to do this, and I would really appreciate some help.

I tried with a for loop,

var i;
for(i = 0; i < instance_number(obj_block); i += 1)
{
blocks = instance_find(obj_block,i);
}

but the instance_find function just arbitrarily chooses an object, so the array is in a random order. I need it to be biased off of the instances x coordinate maybe? Any Ideas would be greatly appreciated. Thank you for you time.
 

Yal

🐧 *penguin noises*
GMC Elder
You could add all objects to a priority queue (ds_priority; look up the manual page Priority Queues) with a with loop, and use x as the priority. Then take each value from the priority queue and put in the array, and it'll be sorted by x.
 

TheouAegis

Member
In said_object's create event or Room Start event or whatever... the point is, this goes in said_object to be run after all other said_objects have been created.

Code:
var X = x;
var ID = id;
var count = 0;
with said_object
{
    if id != ID
    if x < X
        count++;
}
ObjID = count+1;

But Yal's version might be faster. You should test both.
 

Xer0botXer0

Senpai
Well, you are creating them left to right, so why not just increment a variable every time an instance is created. and in that for loop set the variable for the instance to the variable that you're incrementing.
 
L

Liam_Ihasz

Guest
Thanks you guys! Yal answered my question pretty well, as well as helped me learn a bit more about Data structures (I'm still a beginner) Thank you! However, What I actually ended up doing is actually closer to what TheouAegis had. Anyway, sweet. Got it to work. Thank you guys! I should really ask the community more often. :D
 
  • Like
Reactions: Yal

Yal

🐧 *penguin noises*
GMC Elder
I think data structures will be faster since they run compiled commands for sorting and stuff while sorting manually runs interpreted GML, but for a mere 15 instances it shouldn't really make a noticeable difference. As long as it works :3
 
Top