MZ Trying to get a specific State + Variable interaction to work correctly

I'm trying to get a state to tie a enemies health to a variable so another enemy in the same troop can be transformed into it and it's HP remains the same. bonus points if someone can also help me make it so every enemy in the troop dies when a enemy who has this state currently dies.

This is my current code:

<JS On Add State>
target.hp = ($gameVariables.value(94));
</JS On Add State>

<JS On Erase State>
$gameVariables.setValue(94, target.hp);
</JS On Erase State>

<JS Post-Damage As Target>
if (target.hp <= 0 || target.isDead()) {

}
</JS Post-Apply As Target>
Moved to: Plugin Support
target.hp = ($gameVariables.value(94));
You can't do this, hp isn't a variable that you can set. The engine really wants you to go through the gainHp() function, but you can set it directly via target._hp

<JS Post-Damage As Target>
if (target.hp <= 0 || target.isDead()) {

}
</JS Post-Apply As Target>
This wouldn't do anything even if you had code in it, because your start and end notetags don't work.

But it's pretty straightforward:
Code:
<JS Post-Damage As Target>
if (target.hp<=0 || target.isDead())
    $gameTroop.aliveMembers().forEach(enemy => enemy.gainHp(-enemy.hp));
</JS Post-Damage As Target>
The engine really wants you to go through the gainHp() function, but you can set it directly via target._hp
That's what setHp is for, e.g.
JavaScript:
target.setHp($gameVariables.value(94));

I'm not sure if the post-damage tag will run after death, since death typically removes all other states on apply. (I'm guessing that's why the hp <= 0 check is in there?) If that does turn out to be a problem, I imagine you could add a "Resist State: Death" trait to this state, then have the state remove itself after doing its on-death stuff, e.g.

if (target.hp <= 0) { for (const ally of target.friendsUnit().aliveMembers()) { ally.addState(1); } target.removeState(123); }
(Assuming "this state" is state ID 123. If target is always an Enemy then you can just use $gameTroop like Turan suggested instead of target.friendsUnit().)
That's what setHp is for
Forgot about that one 😊
Thanks ya'll it works perfectly now. You know in hindsight I probably shouldn't be trying to code stuff half asleep... That's how you get results like the mess I initially posted lol.

Original thread: https://forums.rpgmakerweb.com/threads/trying-to-get-a-specific-state-variable-interaction-to-work-correctly.158184/