Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Is there a more efficient way to check nearby tile locations for colliders?

Discussion in 'Scripting' started by ryanzec, Aug 2, 2020.

  1. ryanzec

    ryanzec

    Joined:
    Jun 10, 2008
    Posts:
    666
    So am building a turn based game and something I need to be able to track is what nearby tiles are open so I currently have this code:

    Code (CSharp):
    1. var selfPosition = gameObject.transform.position;
    2. var availableNearbyPositions = new HashSet<Vector3>();
    3. var hits = new RaycastHit2D[1];
    4. var layerMask = LayerMask.GetMask(LayerName.CHARACTER) + LayerMask.GetMask(LayerName.GROUND);
    5. var scanRadius = 3;
    6.  
    7. for (int x = -scanRadius; x <= scanRadius; x++) {
    8.   for (int y = -scanRadius; y <= scanRadius; y++) {
    9.    if (x == 0 &amp; y == 0) {
    10.      continue;
    11.    }
    12.    
    13.    var checkPosition = VectorUtility.Round(
    14.      new Vector3(selfPosition.x + x, selfPosition.y + y, 0),
    15.      1
    16.    );
    17.    Physics2D.RaycastNonAlloc(
    18.      checkPosition,
    19.      Vector2.zero,
    20.      hits,
    21.      float.PositiveInfinity,
    22.      layerMask
    23.    );
    24.  
    25.    if (hits[0].collider != null) {
    26.      hits[0] = new RaycastHit2D();
    27.      continue;
    28.    }
    29.    
    30.    availableNearbyPositions.Add(checkPosition);
    31.   }
    32. }
    So this code does give the desired effect however I am wondering if there is a more efficient way to do this. based on my profiling, this piece of code executed for 100 entity that are being tracked takes about 5ms.

    While I might be able to figure out a way to scope down the amount of entities that I do this check for on each turn (and I am open to suggestions on this part too), I liked to know if there is a way I can trim down that 5ms down since that is close to half of the time I want to use for a frame, any suggestions?
     
  2. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    85
    Raycast is way to heavy for such a simple thing.
    Store the tiles in an array. I personally like to use a multidimensional array for this; Tiles[x,y].
    And then use data that links with Tiles[x,y] to determine what is on the tile; if(TilesOpen[x,y]){//this tile is open}.
     
unityunity