• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by AlberellDiPasqua · 6 days ago · unity 2ddestroyphysics2dtopdownoverlap

Cant destroy some objects on overlapcircleall

I have created a script for a "bomb" ability that is supposed to destroy all the coins (they get continously spawned in a random position) in an area but for some unknown some of the coins dont get deleted even on multiple tries. I had the coin prefab in a layer that i put in a layermask for the overlap circle, then to try i removed the layermask and it destroyed other gameobjects just fine but some coins continued not getting destroyed, i also added a condition in wich if the colliders have the coin tag the object with that collider gets destroyed but it still doesnt work.

This is the script for it

  //bomb variables
     [SerializeField] private GameObject bombCenter;
     [SerializeField] private LayerMask layerMask;
     Vector2 point;
 public void Bomb()
     {
         Collider2D[] coins = Physics2D.OverlapCircleAll(point, 15);
         foreach (Collider2D col in coins)
         {
             if (col.tag == "Coin")
             {
                 Destroy(col.gameObject);
                 scoreInt += 1;
             }
 
         }
     }


This is the full script if you need it

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class Player : MonoBehaviour
 {
     //movement control variables
     public Rigidbody2D rb;
     public static float speed = 5f; // increases with the score
     Vector2 movement;
 
     //dash control variables
     private bool dashing = false;
     private float dashTime = 0.15f;
     public static float dashCD = 3f;
     private float nextDashTime = 0f;
     public TrailRenderer trail;
     private float dashSpeed = 20f; // this changes the distance traveled in dashTime
     public AudioSource dashSound;
     private bool canDashSound = false;
     public SpriteRenderer playerSR;
 
     //bomb variables
     [SerializeField] private GameObject bombCenter;
     [SerializeField] private LayerMask layerMask;
     Vector2 point;
 
     //death variables
     public ParticleSystem explosion;
     private bool canExplode = true;
     public Transform playerTransform;
     public static int tolerance;
 
     //sound control variables
     public AudioSource collectCoin;
     public AudioSource BGM;
     public AudioSource deathSound;
 
     // score control variables
     public int scoreInt;
     public Text score;
 
     // scene control variables
     public static bool canLoad = false;
 
     private void OnTriggerEnter2D(Collider2D collect)
     {
         collectCoin.Play();
         scoreInt = scoreInt + 1;
         score.text = scoreInt.ToString();
     }
 
     void Start()
     {
         BGM.mute = false;
         point.x = bombCenter.transform.position.x;
         point.y = bombCenter.transform.position.y;
     }
 
     void Update()
     {
         if (Upgrades.nTolerance == 0)
         {
             tolerance = 20;
         }
 
         movement.x = Input.GetAxisRaw("Horizontal");
         movement.y = Input.GetAxisRaw("Vertical");
         if (Counter.count >= tolerance)
         {
             StartCoroutine(Death());
         }
 
         if (dashing)
         {
             trail.emitting = true;
         }
         else
         {
             trail.emitting = false;
         }
 
         if (Input.GetMouseButtonDown(0))
         {
             Bomb();
         }
 
         // dash ability
         if (Input.GetKeyDown(KeyCode.Space) && Time.time > nextDashTime)
         {
             nextDashTime = Time.time + dashCD;
             StartCoroutine(Dash());
         }
 
         if (Time.time > nextDashTime && canDashSound)
         {
             StartCoroutine(DashCDAnim());
         }
     }
 
 
     public void Bomb()
     {
         Collider2D[] coins = Physics2D.OverlapCircleAll(point, 15);
         foreach (Collider2D col in coins)
         {
             if (col.tag == "Coin")
             {
                 Destroy(col.gameObject);
                 scoreInt += 1;
             }
 
         }
     }
 
     IEnumerator DashCDAnim()
     {
         dashSound.Play();
         canDashSound = false;
         playerSR.color = Color.cyan;
         yield return new WaitForSeconds(0.2f);
         playerSR.color = Color.white;
     }
 
     IEnumerator Dash()
     {
         canDashSound = true;
         dashing = true;
         rb.velocity = movement * dashSpeed;
         yield return new WaitForSeconds(dashTime);
         rb.velocity = movement * speed;
         dashing = false;
     }
 
     IEnumerator Death()
     {
         if (canExplode)
         {
             BGM.mute = true;
             deathSound.Play();
             canExplode = false;
             playerTransform.DetachChildren();
             Destroy(this.gameObject);
             TotalCoins.coins += scoreInt;
             explosion.Play();
             canLoad = true;
         }
         yield return new WaitForSeconds(1.5f);
     }
 
     void FixedUpdate()
     {
         if (!dashing)
         {
             rb.velocity = movement * speed;
         }
     }
 }
 

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by logicandchaos · 2 days ago

I was thinking that maybe the issue is that you are destroying the objects in the list before the loop runs it's full course, you can fix this by using a while loop instead or by adding a delay to the Destroy call.

Change the code in your Bomb method to:

 foreach (Collider2D col in coins)
          {
              if (col.tag == "Coin")
              {
                  Destroy(col.gameObject, 0.1f); //Add delay of .1 sec could try increasing if error persists
                  scoreInt += 1;
              }
  
          }

Or this:

 while (coins.length>0)
          {
              if (coins[0].tag == "Coin")
              {
                  Destroy(coins[0].gameObject);
                  scoreInt += 1;
              }
              else
              {
                    coins.RemoveAt(0);
              }
          }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

176 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

XP and Collision in Unity2D 0 Answers

how to break with a big mass 0 Answers

Physics2D.OverlapCircleAll and OverlapCapsuleAll behaves differently? 0 Answers

Rotate An Object Toward The Direction The Joystick Is Pressed, can you help me? I am stuck 1 Answer

Adding a "paddle bump" to paddle in block breaker game? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges