Scripting to change regions

I recently started using rpgvxa from the humble bundle some time back, and I've been learning ruby and rgss3. This project I'm working on requires me to change a tile's region in-game. I have this script currently:

class Game_Map

   def change_region(mapid, x, y, region)

      targetmap = load_data("Data/Map" + mapid + ".rvdata2")

      targetmap.data[x, y, 3] = ((targetmap.data[x, y, 3] & 255) | (region << 8))

   end 

end 

It runs without errors or crashes, and it returns with the correct 4-bit binary stuff for layer 3. But when I call $game_map.region_id(x, y) after change_region on any of the affected tiles, it returns with what the region was set to before, in the actual editor. This makes me think that I'm missing something to actually push the changes to the map, but I can't find anything about that online. Am I missing something obvious, like a quick function call, or am I completely off on everything here?
I've moved this thread to Script Support. Please be sure to post your threads in the correct forum next time. Thank you.

It can't work that way, because maps are read-only and mapdata is replaced with the original data whenever a new map is loaded. You would have to change the data again whenever the map is loaded. Additionally, the data structure itself needs to be reprogrammed to allow changes after the map is loaded.

There are ways around that, but they require more than a few lines and I'm not a scripter - please wait for a scripter answer to your problem.
You are loading the map data into one variable. Game_Map loads it into one variable. They are not the same variable. So when you change it, you are changing the first variable, not what Game_Map is looking at.


You would need to change $game_map.data (check to see whether that gives you the original table, or if it gives you a copy - you would want it to give you the original).


Then you would also need to ensure every time that map is loaded, the change is remade. You could do that either with a parallel process event conditioned by a switch that's turned on when the change first happens, and does a script call to change the region, then erases itself (so it will rerun every time you return to that map after the switch is initially turned on), or you can save the details in one of the arrays that gets saved along with the player data (I'd suggest Game_System), and have Game_Map check to see if any tiles need to be changed each time it loads.
Alright, glad to know the script itself isn't the problem! I'll work on calling for the original table (and posting to the right forum). The re-call and erase will be easy.

Original thread: https://forums.rpgmakerweb.com/threads/scripting-to-change-regions.46257/