@jkeks
One thing that is worth mentioning is that MZ's editor allows you to use the same name for multiple variables, so if you wish to use an approach like this, you need to be diligent about ensuring that you are giving each variable a unique name.
The existing solutions in this thread are fine if you can guarantee that you will never make any mistakes in naming your variables, and that you will never make a typo in your script calls. However, if you happen to accidentally have two variables with the same name, or if you accidentally use the wrong capitalization or spelling in the variable name in your script call, then they will kinda just quietly let it happen and give you potentially unintended values, which could result in you having bugs in your code that are hard to trace or that you might not ever even notice.
Since I sometimes have a tendency to let myself get sleep deprived to the point where I turn into a muppet, I can't guarantee that I would never make such a mistake, so I'd personally prefer a solution that explicitly lets me know when I'm doing something wrong. That being the case, I'd go for something a bit more robust, along these lines:
Spoiler: Nolonar's Solution Modified
JavaScript:
var jkeks = jkeks || {};
jkeks.getVarIndex = function(name) {
let index = 0;
for (const [key, value] of Object.entries($dataSystem.variables)) {
if (value === name) {
if (index !== 0) {
throw new Error(`There are multiple variables with the name: ${name}`);
}
index = key;
}
}
if (index === 0) {
throw new Error(`There is no variable with the name: ${name}`);
}
return index;
};
jkeks.getVarByName = function(name) {
return $gameVariables.value(this.getVarIndex(name));
};
jkeks.setVarByName = function(name, value) {
$gameVariables.setValue(this.getVarIndex(name), value);
};
@ct_bolt
I'm in sleep-deprived-muppet-mode right now, so I could be looking at it wrong, but it seems to me that you've got an error in your plugin, when it comes to switches. I think you've got the
Game_Switches methods trying to pull an index out of
$dataSystem.variables.