Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Refactoring logic from IJobForEachWithEntity#Execute to private method hangs Unity

Discussion in 'Entity Component System' started by mannyhams, Jul 6, 2019.

  1. mannyhams

    mannyhams

    Joined:
    Feb 6, 2015
    Posts:
    34
    Greetings, lovely Hive Mind!

    I wrote a job which instantiates a bunch of prefabs with some buffer space in between them using IJobForEachWithEntity (based off the SpawnFromEntity example). It works fine, but after a simple refactor where I've split out some logic into a method on the job struct, Unity hangs during play mode and CPU usage spikes and I have to force quit.

    Here's the diff, using Unity 2019.1.8f1. Any ideas what's going on? I'm new to both Unity and game development, so please don't hesitate to point out if you see something off in there.

    Thanks! :)
     
  2. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    Random is a struct. So it's being run with the same seed on every call to findValidPos. Pass it by reference and it should work. Although using while around something that might never return like this will invariablly get you in trouble. Use a for loop to constrain it and have a fallback, even if it's just default float3. Better then locking up the game.

    By the same token every job run is using the same seed also, which might be ok in your case but as a general rule you would want something like this in Update that you pass to your job struct:

    Code (csharp):
    1.  
    2. var random = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(int.MinValue, int.MaxValue));
    3.  
     
    mannyhams likes this.
  3. mannyhams

    mannyhams

    Joined:
    Feb 6, 2015
    Posts:
    34
    Ah great thanks for all this! Passing by reference works as you say, I forgot how this works in C# and assumed the struct was passed by reference like a class instance.

    Also agree about reusing the same Random across all job executions - in this case I wasn't worried since the system is only intended to run once.

    Also agree about better handling for findValidPos - this is just a playground so I was happy to leave the code as is since the probability of not being able to find a valid position is very low given my testing inputs. In production code, I was thinking I would have the function make a best effort to find an open position before giving up and throwing after some (large) number of tries.