Search Unity

Need help with multi-threading.

Discussion in 'Editor & General Support' started by Affy, Sep 10, 2014.

  1. Affy

    Affy

    Joined:
    Aug 19, 2014
    Posts:
    13
    Hello! I'm new to Unity (new to C# as well in fact), have been using it for a few weeks now. So far, I love the engine!

    Anyway, I've been experimenting with A* pathfinding for my RTS game and it became evident that I needed to do the path calculations on a separate thread to improve performance.

    So, knowing little about threads I started reading about it but then I stumbled upon this script which allows me to run a closure/anonymous function in another thread. I'm sure others have seen the script, I think it's similar to the "Loom" thing on the asset store.

    Anyway, here is essentially what I'm doing with the script:

    Here's what I'm doing in psuedocode:

    Code (CSharp):
    1. //Navigator.cs
    2. void moveTo(Node target) {
    3.     this.path = pathfinding.findPath(transform.position, target);
    4. }
    5. void Update() {
    6.     if (this.path != null) {
    7.    //move along the current path
    8.     }
    9. }
    10.  
    11. //Pathfinding.cs, here I'm using the Loom script, to run the path calculation on a separate thread.
    12. Path findPath(from, to) {
    13.     Path path = new Path(from, to)
    14.  
    15.     Loom.RunAsync(() => {
    16.         List<Node> open = new List<Node>();
    17.         List<Node> closed = new List<Node>();
    18.         while(open.Count > 0 && path.cancelled = false) {
    19.            //A* algorithm...
    20.         }
    21.     });
    22.  
    23.     return path;
    24. }

    The lockup/freeze mostly happens when I have several units generating paths simultaneously. E.g 3-4 units.

    So, the question is.. what's the issue? Is this because I'm initializing/destroying the Lists? (open & closed lists).

    Maybe I should make a queue system and put all paths on a queue, then I could use the same Open & Closed Lists.

    I suppose I could refrain from having the nodes in the Path object too and just return an array of vector3's instead. (I don't need to have access to the nodes in the navigator.

    Anyway, if you can help or point me in the right direction it would be much appreciated. Thanks.

    Edit
    After some thinking, I decided to do two things. First, pre-allocate the Path objects as well as the open/closed lists.

    Then, I implemented a queue system. It's slightly complicated but works very well but it can only process one path at a time. This might be OK, time will tell.
     
    Last edited: Sep 10, 2014