Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Coding and optimizing a power system

Discussion in 'Scripting' started by thatdevnoTHATdev, Apr 26, 2024.

  1. thatdevnoTHATdev

    thatdevnoTHATdev

    Joined:
    Dec 20, 2021
    Posts:
    3
    I have a 2d tile-based game. I plan to add a power system in the near future, something along the lines of Oxygen Not Included's power system with wires.

    The wires will be tiles in a seperate tilemap in the game, but in the code they will be something else.
    What I plan to do is to make the "wires" some nodes in an array (which corresponds to the map) and have the connections be stored in another array, basically a graph. There will be power sources and all power consumers that are connected to a wire system with a power source will be powered. Issue is, I wouldn't want the power consumers to constantly check whether they are connected to a power producer or vice versa.

    I think I'd do this by making the consumers memorize whether they are connected to a power source, but I don't know how to make this check fast enough considering there can be multiple power consumers/sources...

    The map (at the current state) consists of 300 tiles horizontally and 190 tiles vertically. I'll attach an image of the game too:

    upload_2024-4-26_16-53-38.png
    (entire map):
    upload_2024-4-26_16-54-32.png

    If more details are required, I'll gladly provide some!
    Any help is appreciated!
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    373
    Well, it seems like you could use any graph traversal algorithm. You don't need to constantly check connection. You could do that check when you change your graph, and you could optimize it further by reevaluating connection only for nodes that are reachable for changed.
    Let's say you add or remove node, you go to all its neighbours until you find any power producer and then find all reachable consumers and set them as active or not active.
    I believe that could be optimized further, but these are just first ideas that came to my mind.
    If you need many producers for many consumers I think you could make some kind of node cost which will say how many producers are connected.
    You could possibly use multithreading to improve performance, even if it means running the check over a couple of frames.
     
    PraetorBlue and thatdevnoTHATdev like this.