Legacy GM Using instance created variables inside step event

I

iLeD

Guest
Hi there, new to this forum :) hope you can help.

I can't seem to figure this out, maybe because it's 03:32 but anyway here's what I'm trying to do. I have a random head sprite that creates a random body sprite on creation using a specific instance:

Code:
//inside head object
var inst = 0;
inst = instance_create(x, y, obj_enemy_body);
with (inst)
   {
   inst.x = x;
   inst.y = y;
   }
This puts the body and head in the same place. Great! Now in the bodies step event he starts wandering about randomly so I want the head to follow. If I reference the inst.x / inst.y in the step or end step event I get a set before reading error. Any ideas?

Thank you!
 

FrostyCat

Redemption Seeker
Save the instance ID in an instance variable and you won't get that error then.
Code:
with (instance_create(x, y, obj_enemy_body)) {
  head = other.id;
}
Now you can access head from the body and control it later.
 
I

iLeD

Guest
Brilliant, thank you I'll give this a shot :)

BTW sorry for posting in the wrong section :)
 
I

iLeD

Guest
Right so I've put that code into my obj_enemy_head and in the step event on obj_enemy_body I've added

Code:
head.x = x;
head.y = y;
Still gives an error, obviously I'm doing that wrong. I'm assuming I'm calling head wrong, should it be the same name as my obj_enemy_head? :) Many thanks for the help.
 

TheouAegis

Member
Is it even the correct error? It is not uncommon that somebody looked at an error message and claimed that their code is broken when the message said something else and the code works just fine.
 
Code:
//inside head object
var inst = 0;
inst = instance_create(x, y, obj_enemy_body);
with (inst)
   {
   inst.x = x;
   inst.y = y;
   }
If I reference the inst.x / inst.y in the step or end step event I get a set before reading error.
Remove var from the code and you can reference inst. var makes the variable only exist in the code block.

Also the code
Code:
with (inst)
   {
   inst.x = x;
   inst.y = y;
   }
is the same as inst.x = inst.x; inst.y = inst.y;.
 

FrostyCat

Redemption Seeker
This is what the completed system should look like.

obj_enemy_head
Create:
Code:
with (instance_create(x, y, obj_enemy_body)) {
  head = other.id;
}
obj_enemy_body Create:
Code:
head = noone; //Override
obj_enemy_body Step:
Code:
if (instance_exists(head)) {
  head.x = x;
  head.y = y;
}
Since head is supposed to be an instance variable that lasts the life of the instance, make sure var is never used with it anywhere in this context.
 
I

iLeD

Guest
Thank you so much FrostyCat! It worked like a charm. Learn something new every day.
 
Top