Page 1 of 1

How to replace an elevated rail with a custom elevated rail

Posted: Mon Dec 23, 2024 8:18 pm
by theblackswitch
Hi,

I'm making a mod to hide elevated rails using a keybind so you can see behind them. Everything worked very well until I tried to replace a normal elevated-curved-rail-a with my new hidden-elevated-rail-curve-a which is just a deep copy of the elevated-curved-rail-a with different textures. It seems like the elevated rails do get replaced but only when the original rail isn't connected to any other rails. So the replace code works but when the newly created rail connects to any other rail, it cannot be replaced. Weird... Does someone know why this happens?

Here is my code:

Prototype

Code: Select all

require ("__hide-elevated-rail-keybind__.prototypes.hidden-rail-pictures")

local hidden_rail = table.deepcopy(data.raw["elevated-curved-rail-a"]["elevated-curved-rail-a"])

hidden_rail.name = "hidden-elevated-rail-curve-a"

hidden_rail.selection_priority = 1
hidden_rail.pictures = elevated_rail_pictures("curved-a")
hidden_rail.fence_pictures = elevated_rail_fences_pictures("curved-a")


data:extend({hidden_rail})
Control.lua

Code: Select all

function replace_elevated_rails (original, replace, player)
    local entities = game.surfaces[player.surface_index].find_entities_filtered{position = player.position, radius = 100, name = original}
    for i, entity in ipairs(entities) do
        local new = entity
        game.print(player.surface.create_entity{name})
        entity.destroy()
    end
end

script.on_event("on_tick",
    function(event)
        local players = game.players
        for i, local_player in pairs(players) do
            local original = "elevated-curved-rail-a"
            local replacement = "hidden-elevated-rail-curve-a"
            local s = local_player.surface
            for chunk in s.get_chunks() do
                local entities = s.find_entities_filtered{name=original, area={{chunk.x*32, chunk.y*32}, {(chunk.x+1)*32, (chunk.y+1)*32}}}
                for _, entity in pairs(entities) do
                    s.create_entity{name=replacement, position=entity.position}
                    entity.destroy()
                end
            end
        end
    end
)