[SOLVED] Can you chain together variables accesses in objects

S

Skyeward

Guest
Probably a badly worded title, I'll explain better below:

Let's say I have obj_player and obj_weapon. obj_player has a variable called weaponID, which is the instance id of obj_weapon. To set or change this id I can access it from other objects via obj_player.weaponID, but what if I want to change variables inside obj_weapon itself? Can you chain together these periods so as to say obj_player.weaponID.ammoCount for example to change variables in the weapon? Or is this way of accessing variables limited to just one period?

Thanks!
~Skyeward
 

PNelly

Member
Why don't you just try it and see if works?

I can't actually remember if it will, but even if it doesn't you can break it up into multiple commands and it should work fine.

Code:
var _weapon_id = obj_player.weaponID; // variable reference to first object
(_weapon_id).ammo += number; // variable reference to second object
 
S

Skyeward

Guest
I don't have Game Maker on the laptop I'm currently on, I'm attempting to write a script outside of GM that will hopefully work if I copy and paste it once I'm back on my own computer ^^.

Thanks for your suggestion, if I can't chain together variables to be more succinct then I'll certainly be using that.
 

Hyomoto

Member
If the references are all good, you can chain them together until they fail.
Code:
var sprite = object_id.weapon_id.ammo_id.sprite_index
However! While this solution is fine, you must keep in mind if that any point it doesn't work, it will fail and crash. Thus @PNelly's suggestion comes into play. For example:
Code:
if object_id.weapon_id != undefined {
  sprite = object_id.weapon_id.ammo_id.sprite_index;

} else { sprite = -1 }
You can break it up however you need to, but yes, you can chain them together. You can even do something like:
Code:
var sprite = (find_object_gun( object_id )).ammo_id.sprite_index
Just keep in mind, however, that object_id, weapon_id, and ammo_id should all be instance ids. A lot of built-in functions in GML will take either an instance id or an object id, but when you are trying to reference variables this will crash. You need to store the instance id of the object you are trying to reference.
 
S

Skyeward

Guest
Thanks, I really wasn't expecting it to work, I thought it was a long shot!
 

Hyomoto

Member
Ah, sorry @Skyeward , I misread your question. You -can- do this to change all instances of object_weapon. So:
Code:
object_weapon.bullet_count = 15
Is functionallity equivalent to:
Code:
with (object_weapon) { bullet_count = 15 }
I don't believe you can chain together references after that, and like I said, if you are trying to get a variable you have to be precise. But yes, it will work the way you asked as well. The object itself doesn't exist, so you can't, for example, change all the variables before an instance is created from it. You have to create the instance, and then change it's values.
 
Top