Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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
0
Question by revvan · Aug 08, 2016 at 03:44 PM · 2dtriggerscollision2dexplosionbomb

How to Destroy specific objects using OnTrigger2D?

In my game there are blocks, and glass blocks are the only type of block that will get destroyed in an explosion. Here's my code:

     void OnTriggerStay2D(Collider2D other){
         if (other.gameObject.GetComponent<CollisionHandler>()){
             isColliding = true;
             if (explosionDelay <=0){
                 if (other.gameObject.tag == "glass"){
                     Destroy (other.gameObject);
                     Destroy (bomb);
                     Debug.Log ("boomglass");
                 } else {
                     Destroy (bomb);
                     Debug.Log ("boom");
                 }
             }
         }
     }

At the moment if there's a glass block in the bomb's radius, it will destroy the bomb and the glass block. My problem is that if there's a block that isn't glass the bomb won't "explode" until something comes into it's radius. I have a FixedUpdate which handles the counting down of the bomb and makes the bomb explode if it "isn't colliding". See code:

     void FixedUpdate () {
         explosionDelay -= Time.deltaTime;
         if (explosionDelay <=0){
             if (isColliding == false){
                 Destroy (bomb);
                 Debug.Log ("boomupdate");
             }
         }
     }

I've been using unity for only a few days so I'm sorry if it's something really simple :P

Answered! Thanks to @lunoland <3 you da best

Comment
Add comment · Show 1
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
avatar image Cherno · Aug 08, 2016 at 09:01 PM 0
Share

$$anonymous$$y tip: Ins$$anonymous$$d of continually checking for collisions via OnTriggerStay, use Physics.BoxCast or SphereCast ins$$anonymous$$d. When the timer eraches zero, call the Spherecast at the bomb's position, and go through each returned collider. If one is a glass block, destroy it. After all this, destroy the bomb as well.

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by lunoland · Aug 08, 2016 at 09:59 PM

You'll definitely want to use some flavor of ray casting instead of collision; It models your solution better (easier to understand) and will give you better performance. I would also prefer a Coroutine (https://docs.unity3d.com/Manual/Coroutines.html) over FixedUpdate() here for the same reasons.

The gist of Cherno's suggestion is correct, but in 2D you'll want to use one of the Physics2D overlap functions. Here's some sample code (warning: untested):

 class Bomb : MonoBehaviour {
     public float explosionDelay;
     public float explosionRadius;
 
     public void BeginCountdown() {
         StartCoroutine(Countdown());
     }
 
     IEnumerator Countdown() {
         yield return new WaitForSeconds(explosionDelay);
         Explode();
     }
 
     void Explode() {
         Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, explosionRadius);
     
         foreach (Collider2D collider in colliders) {
             Block block = collider.GetComponent<Block>();

             if (block != null && collider.gameObject.tag == "glass") {
                 block.Explode();
             }
         }
         
         Destroy(this.gameObject); // Remove the object this script is attached to. The "this" keyword is optional, but I think it reads a little more clearly.
     }
 }

To make a bomb explode, you simply get a reference to the Bomb script and call the BeginCountdown() function, like so:

yourGameObject.GetComponent<Bomb>().BeginCountdown();


I would also suggest using the following pattern of adding an enumeration-type variable to represent the material in your block class, as opposed to relying on tags:

 class Block : MonoBehaviour {
     public enum Materials { None, Glass, Stone }; // Add your other block types here.
     public Materials material; // Now for each of your block objects, you can assign this value from a drop down in the inspector (instead of having to make a tag for each material).
 
     public Explode() {
         // Put whatever you want to happen when the block explodes here!
         Destroy(this.gameObject);
     }
 }

If you implement this, then the code that checks for a glass block in the Bomb class would change to

if (block != null && block.material == Block.Materials.Glass) { /* ... */ }

Comment
Add comment · Show 6 · 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
avatar image revvan · Aug 09, 2016 at 09:09 AM 0
Share

Thanks for the reply! I'll definitely try your method out and see what I can do with it :) it also suits my needs much better, because it allows me to choose what happens to each kind of block better. Thanks again!

avatar image lunoland revvan · Aug 09, 2016 at 03:24 PM 0
Share

No problem! If this is the most helpful answer, click the "accept" button at the bottom of the answer so your question will appear as answered.

avatar image revvan lunoland · Aug 09, 2016 at 03:29 PM 0
Share

I finally tried to implement the code and now it destroys glass blocks correctly! Yay! But now the bomb doesn't explode. Also it gives me this error:

 NullReferenceException: Object reference not set to an instance of an object
 Bomb.Explode () (at Assets/Scripts/Bomb.cs:22)


Any ideas? I tried to add some kind of != null into the if statement but it didn't seem to help.

EDIT: Forgot to add, this is the line in question (I think):

             if (collider.GetComponent<Block>().material == Block.$$anonymous$$aterials.Glass) {
Show more comments
avatar image revvan · Aug 09, 2016 at 05:02 PM 0
Share

Hey I tried implementing your code and now it destroys glass blocks correctly! Yay! But the bomb doesn't explode. Also it gives me this error when the timer hits 0:

 NullReferenceException: Object reference not set to an instance of an object
 Bomb.Explode () (at Assets/Scripts/Bomb.cs:22)

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.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

2D Triggers and Collisions not working as expected. 2 Answers

Unity2D collision problem 3 Answers

Box Collider 2d Not Colliding 0 Answers

How to calculate angle between 2D objects and use the result? 0 Answers

Using a mask shader for creating pop/explosion effect? 1 Answer


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