• 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 bhuddaboom · Dec 22, 2015 at 12:11 PM · 2d gameoverlapsphere

2D Area of Effect Script

Hi, this is my first attempt at an AoE script. I attached the following to my rockets to do damage and apply an explosion force effect to the enemy it hits and any other enemies within a certain radius:

using UnityEngine; using System.Collections;

public class RocketExplosion : MonoBehaviour {

 public float expRadius = 10f;            // Radius within which enemies are damaged.
 public float expForce = 100f;            // Force that enemies are thrown from the blast.
 public GameObject soundPrefab;            // Audioclip of explosion.
 public GameObject explosionPrefab;        // Prefab of explosion effect.
 public float Damage=100;
 
 

 void Start ()
 {
     

 }
     
 void OnTriggerEnter2D(Collider2D other){
     if(other.gameObject.tag == "Enemy"){

     
     
     // Find all the colliders on the Enemies layer within the expRadius.
     Collider2D[] enemies = Physics2D.OverlapCircleAll (transform.position, expRadius, 1 << LayerMask.NameToLayer("EnemyLayer"));
     
     // For each collider...
     foreach(Collider2D en in enemies)
     {
         // Check if it has a rigidbody (since there is only one per enemy, on the parent).
         Rigidbody2D rb = en.GetComponent<Rigidbody2D>();
         if(rb != null && rb.tag == "Enemy")
         {
             // Find the Enemy script and apply damage.
             rb.gameObject.GetComponent<HealthEnemy>();
             HealthEnemy hp=(HealthEnemy)transform.GetComponent("HealthEnemy"); 
             if(hp){
                 if(hp.CurrentHealth<=hp.MaxHealth){        
                     hp.CurrentHealth=hp.CurrentHealth-Damage;
                     
                 }
             }
             
             // Find a vector from the rocket to the enemy.
             Vector3 deltaPos = rb.transform.position - transform.position;
             
             // Apply a force in this direction with a magnitude of expForce.
             Vector3 force = deltaPos.normalized * expForce;
             rb.AddForce(force);
         }
     }
 }

     

     // Instantiate the explosion prefab.
     Instantiate(explosionPrefab,transform.position, Quaternion.identity);
     
     // Play the explosion sound effect.
     Instantiate(soundPrefab, transform.position,transform.rotation);
     

 
 }

}

Now the explosion is not going off half the time, and it doesn't cause damage to the enemies. The explosion force effect seems to work most of the time though. What am I doing wrong?

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

2 Replies

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

Answer by OncaLupe · Dec 23, 2015 at 12:10 AM

Well the problem with not applying damage to enemies is from this:

 rb.gameObject.GetComponent<HealthEnemy>();
 HealthEnemy hp=(HealthEnemy)transform.GetComponent("HealthEnemy");

The first line is doing nothing but wasting time. You're retrieving the HealthEnemy script, but not storing the reference or doing anything else with it. The second line is checking for a component by name on the same object as the script (the rocket in this case) because you're using 'transform'. Both these lines should be replaced by this:

 HealthEnemy hp = rb.GetComponent<HealthEnemy>();

There's no need to go through 'gameObject' as you can search for a component from other component references.

Also, should the AoE only apply if the missile hits an enemy directly? The tag check at the start of OnTriggerEnter2D() is wrapping the entire damage/force section, so if the rocket hits something other than an enemy, no damage or force would be applied even if one was within range.

As for the explosion effect not going off, I'm not sure. The Instantiate()s should be working every time it triggers. I'd suggest adding a Debug.Log to the start of the OnTriggerEnter2D() to see if it's even triggering when the effect doesn't happen.

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
avatar image
0

Answer by bhuddaboom · Dec 23, 2015 at 04:36 PM

Thank You kindly OncaLupe. This works perfectly now, i didn't even think about the tag issue, but yes, I do want the AoE damage if i hit walls etc. The issue with the explosion not triggering was fixed by making the collider on the rocket a bit bigger.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

2D Area of Effect Script - OverlapCircle not working 1 Answer

What happens when i select for android "ETC1 (split alpha channel)", but disable sprite packer for builds 0 Answers

2D Endless runner spawning on top of each other? 0 Answers

ArgumentException: Input Button right is not setup. 1 Answer

Where could I start with making a level editor where you can create your own terrain in Unity 2D? 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