Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Unity 4.6.1f1 Freeze after Physics2D.OverlapCircleAll()

Discussion in 'Scripting' started by JPCannon, Dec 12, 2014.

  1. JPCannon

    JPCannon

    Joined:
    Sep 25, 2013
    Posts:
    37
    Hi. When I use Physics2D.OverlapCircleAll() script in my game, when it has to be done all program get freeze and i must restart it. I found that hitColliders.gameObject.GetComponent<HealthScript>() is freezing program but i dont know why. It`s works few time and after this I always get freeze. Box Collider is in the same object where is HealthScript script. I shoud write this in another way?

    Code (CSharp):
    1.     void ExplodingSpearSkill() {
    2.         if(gameObject.transform.position.y < Screen.height*0.1f) {
    3.             ExplosionDamage(gameObject.transform.position, PlayerActiveSkills.explodingSpearStats[0]);
    4.             Destroy(gameObject);
    5.         }
    6.     }
    7.  
    8.     void ExplosionDamage(Vector3 center, float radius) {
    9.         Collider2D[] hitColliders = Physics2D.OverlapCircleAll(center, radius);
    10.         //Collider2D[] hitColliders = Physics2D.OverlapCircleNonAlloc(center, radius, hitColliders);
    11.         int i = 0;
    12.  
    13.         Debug.Log("BUM : " + radius + " " + hitColliders.Length);
    14.         while (i < hitColliders.Length) {
    15.             if(hitColliders[i].gameObject.GetComponent<HealthScript>() != null) {
    16.                 Debug.Log("BUUUUUUM");
    17.                 hitColliders[i].GetComponent<HealthScript>().HP -= 100;//gameObject.GetComponent<ShotScript>().damage*PlayerActiveSkills.explodingSpearStats[1];
    18.                 i++;
    19.             }
    20.         }
    21.     }
    SOLUTION.
    Sorry for this. I forget i have in scene unit which attack monsters by explosion and it collider was in array to. But my attacking unit dosent have healthScript :) so thats all problem.
     
    Last edited: Dec 12, 2014
  2. Megolas

    Megolas

    Joined:
    Apr 6, 2013
    Posts:
    25
    Not the problem - you should move i++ from inside the if, otherwise it will just keep retrying forever, and unity will crash.

    Another solution would be to use
    while(i++ < hitColliders.Length) {