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

Question Physics2D inside Jobs or other concurent solution

Discussion in 'Physics' started by StoneWillFall, Apr 29, 2023.

  1. StoneWillFall

    StoneWillFall

    Joined:
    Nov 9, 2017
    Posts:
    4
    Hello,

    I have created an algorithm for generating movement graphs in my game. Some of the MonoBehaviour objects use it when they need to move to a specific destination.
    It is using Physics2D cast and overlaps during process.

    Initially, the algorithm was synchronous, but it caused significant frame drops.

    I don't require the graph to be generated in the same frame when movement is ordered, so I started using a Coroutine with IEnumerator<List<Vector2>> and multiple yields within the algorithm. This solution is quite ok, but for a large number of objects, it reduces the frame rate, so it is not sufficient.

    I discovered Jobs in Unity and attempted to implement my algorithm as an IJob. Unfortunately, it seems that using it with physics is not possible. For example:

    Code (CSharp):
    1. public void Execute()
    2. {
    3.    ...
    4.    Physics2D.OverlapCircle(position, RADIUS, ~(LayerMask.GetMask("Character")));
    5. }
    throws an exception:
    UnityException: NameToLayer can only be called from the main thread.

    And after removing LayerMask:
    UnityException: get_queriesHitTriggers can only be called from the main thread.


    I also tried using Commands within my Job (though they are used for 3D physics, I assumed I could use them anyway in 2D?):

    Code (CSharp):
    1. public void Execute()
    2. {
    3.   ...
    4.   SpherecastCommand.ScheduleBatch(commands, results, 1).Complete();
    5. }
    But this also doesn't work:
    UnityException: ScheduleSpherecastBatch can only be called from the main thread.


    Is there any way to run my algorithm, which utilizes Physics2D casts and overlaps, as an asynchronous Job on other threads to avoid frame drops?
     
    Last edited: Apr 29, 2023
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,316
    No. 2D queries can only run on the main thread.