Adding a state to targets with elemental weaknesses?

Hey guys, I have something that seems fairly simple but I can't quite figure out how to get it to work right. Basically as the title says, I want to be able to add chance to cause a stun state, to targets when they are hit with an attack element they are weak against.

I've searched the forums and found this awesome plugin code that Tsukihime came up with about a year ago. But it's giving me trouble. Mainly for some reason, instead of waiting to be hit from an elemental attack, if an actor has a skill that does extra damage to an enemy, the enemy will just automatically become stunned at the beginning of the encounter.

So currently it has a 35% chance to inflicting the state at the start of the battle. Interesting enough, if the target doesn't receive the stun state at the beginning, the code works as intended! Anyone have some insight on how to edit this code to make it wait for a hit? Or is there an even better way to go about it?

Code:
(function() {

var TH_GameAction_calcElementRate = Game_Action.prototype.calcElementRate;
Game_Action.prototype.calcElementRate = function(target) {
    var rate = TH_GameAction_calcElementRate.call(this, target);
    if (rate > 1) {
       // random number between 0 and 1
       if (Math.random() < 0.35) {
         target.addState( 13 )
      }
    }
    return rate;
};
})();
Instead of editing calcElementRate, why not use Buffs & States Core and Auto Passive States to give enemies a passive state which has a <custom respond effect> notetag which checks whether the action hit, and if so stuns the target if the random check succeeds?
Instead of editing calcElementRate, why not use Buffs & States Core and Auto Passive States to give enemies a passive state which has a <custom respond effect> notetag which checks whether the action hit, and if so stuns the target if the random check succeeds?
That seems like it could be a good idea!

But would I be able to generalize with it? Say, make one state that checks for elemental weaknesses? Or would I have to make a custom state for each elemental weakness?

I'm no scripter, so my knowledge of what the game can and can't calculate is weak.
You can put any javascript code into the notetags using Yanflys Plugins, so you should be able to do almost anything. I'm not much of a scripter myself but I'd say look over Yanfly's Tips and Tricks videos, check the code on their site and use bits of their code to make your custom states 🙂
As Zemtax said, the limit is essentially your imagination and knowledge of Javascript. You can have one state that checks for element weakness based on the element of the attack that hit.

Original thread: https://forums.rpgmakerweb.com/threads/adding-a-state-to-targets-with-elemental-weaknesses.77545/