Search Unity

Question Has something changed in Physics.OverlapShere() recently?

Discussion in 'Scripting' started by Rajmahal, Apr 14, 2021.

  1. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Hi,

    I'm running into a problem where the code for my game is no longer working as expected in Unity 2019 onwards. I'm not sure exactly which version caused it to stope working. I have an editor script that uses Physics.OverlapShere to draw a sphere and detect adjacent Tile objects and then add those to a list of Tile objects called Neighbors. For some reason, in recent versions of Unity, the Neighbors list is always empty despite the code below running:

    Code (CSharp):
    1. //set neighbour
    2.             for(int i=0; i<allTiles.Count; i++){
    3.                 Tile hT=allTiles[i];
    4.                 Vector3 pos=hT.transform.position;
    5.                 Collider[] cols=Physics.OverlapSphere(pos, gridSize*gridToTileSizeRatio*0.6f);
    6.                 List<Tile> neighbour=new List<Tile>();
    7.                 foreach(Collider col in cols){
    8.                     Tile hTile=col.gameObject.GetComponent<Tile>();
    9.                     if(hTile!=null && hT!=hTile){
    10.                         neighbour.Add(hTile);
    11.                     }
    12.                 }
    13.                 hT.SetNeighbours(neighbour);
    14.             }
    Can anyone tell me what I need to change to get this working? The code has no compile errors, it just doesn't find any of the tiles and add them as it does in older versions of Unity.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Can't really give you any advice other than normal debugging advice. Usually in these situations you've changed something else in your project that you thought was minor or unrelated and turned out to affect this.

    In your case, either step through with a debugger or add some longs. This is the information you should focus on:
    • Is this code running at all?
    • What, if anything, is in the
      cols
      array returned from OverlapSphere?
    • What is the value of
      hT
      at the time?
    • Why are tiles from cols not making it through the is statement on line 9?
     
  3. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Thanks ... will do. You're probably right. What I'm noticing is that all the tiles in the grid (allTiles) are added as neighbours to one of the tiles only.
     
  4. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Turns out it was the same issue as this person ran into:

    Physics.OverlapSphere issue - Unity Forum

    So I did the same thing he did and split out the process to have one button create the grid of tiles and then another button to populate their neighbours and the code worked fine.