Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 TheIrishKraken · Jan 02, 2021 at 12:01 AM · 2d gametriggersenemydamage

Press a key to damage all enemies tagged as Enemy separately

My player character has is a trigger and uses the below code to detect enemies

protected void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Enemy")) { enemyInRange = true; collision.gameObject.GetComponent().DepleteHealth(1); } }

This works fine when I move my player over the enemy multiple times it take 1 point of damage off them which is fine. But what I want is to only call that DepleteHealth() method when the player presses the E key instead. I tried to do it inside the update method but only works on one enemy, when you move your player over to enemy number 2 you get an error saying that the referenced object was destroyed which is correct because Enemy 1 was, my code cant register that the player is in front on Enemy 2 now.

I cant figure out how to kill enemy 1 then kill enemy 2 when I press the E key. alt text

capture.png (43.8 kB)
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

4 Replies

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

Answer by yummy81 · Jan 03, 2021 at 10:07 AM

I reproduced your problem. I created Player object with the Player script and a couple of enemies with the EnemyHealth script attached to each of them. Player script contains the list of enemies that are currently within the range of the collider. The list is static because each enemy has to remove itself from the list when destroyed. That takes into consideration the case when the enemy would be destroyed not by pressing E key, but somehow else. Hope that helps. Player script:

 public class Player : MonoBehaviour
 {
     public int damage = 1;
     
     public static List<EnemyHealth> enemiesInRange = new List<EnemyHealth>();
     
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.E))
             for(int i = enemiesInRange.Count - 1; i >= 0; i--)
                 enemiesInRange[i].Deplete(damage);
     }
     
     void OnTriggerEnter2D(Collider2D collision)
     {
         if (collision.gameObject.CompareTag("Enemy"))
         {
             var enemyHealth = collision.GetComponent<EnemyHealth>();
             if (enemyHealth!=null && !enemiesInRange.Contains(enemyHealth))
                 enemiesInRange.Add(enemyHealth);
         }
     }
     
     void OnTriggerExit2D(Collider2D collision)
     {
         if (collision.gameObject.CompareTag("Enemy"))
         {
             var enemyHealth = collision.GetComponent<EnemyHealth>();
             if (enemyHealth!=null && enemiesInRange.Contains(enemyHealth))
                 enemiesInRange.Remove(enemyHealth);
         }    
     }
 }

EnemyHealth script:

 public class EnemyHealth : MonoBehaviour
 {
     public int health;
     int maxHealth = 3;
     
     void Awake()
     {
         health = maxHealth;
     }
     
     public void Deplete(int damage)
     {
         health -= damage;
         if (health <= 0)
             Destroy(gameObject);
     }
     
     void OnDestroy()
     {
         if (Player.enemiesInRange.Contains(this))
             Player.enemiesInRange.Remove(this);
     }
 }

Comment
Add comment · Show 1 · 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 TheIrishKraken · Jan 04, 2021 at 08:45 PM 0
Share

Thank you so much. This was exactly what I was looking for works perfectly now, I read people saying to use lists for this but I wasn't sure how to implement it into my game properly.

Thanks for taking the time to help :)

avatar image
0

Answer by PilgrimFlowers · Jan 02, 2021 at 02:47 AM

A bit of a silly question, but I know I've made this mistake before: are both/all of your enemies marked with the tag "Enemy"? The other thing I would consider is using the method OnTriggerStay2D which checks continually while the trigger is active. So:

 private void OnTriggerStay2D(Collider2D collider)
 {
     if (collider.tag == "Enemy")
     {
         //Your damage function
     }
 }

What I also may suggest is switching it around. What I mean is give the enemy objects a trigger box collider and run the collider check from the enemy checking if the Player is in the collider instead of checking if the Enemy is in the Player's collider (which is what I think you're doing given that you're checking for tag "Enemy"??)

Comment
Add comment · Show 1 · 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 PilgrimFlowers · Jan 02, 2021 at 02:52 AM 0
Share

This is what I would do on my Enemies' collider checks. This checks first that an object (specifically labelled "Player" is inside the collider, and for every frame that the object is within the collider, then while that is true, checks if the E key has been pressed, and then does your damage, but only once per key press. This will apply for all colliders that the Player is within as well (allowing to damage multiple enemies at once)

private void OnTriggerStay2D(Collider2D collider) { if (collider.tag == "Player") { if(Input.GetKeyDown(KeyCode.E) { //Your damage function } } }

avatar image
0

Answer by TheIrishKraken · Jan 02, 2021 at 03:11 AM

Hello

Thanks for the response. Yes both are tagged with Enemy. I have tried switching around already but no good.

You cant call Input.GetKeyDown inside OnTriggerStay or Enter, must be called in the Update() method.

This should seem easy in theory but I cant wrap my head around what the solution might be. Once I kill enemy 1 Unity still thinks I am trying to kill enemy 1 when I am trying to kill enemy 2.

This code below works perfectly when I touch my player off both enemies one after another, but I need to alter it to only kill when I press the E key. alt text


capture.png (12.6 kB)
Comment
Add comment · Show 2 · 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 prakyathd801 · Jan 02, 2021 at 06:22 AM 0
Share
     public KeyCode E; //select key "E" in inspector
     bool isEpressed = false;
     void update()
     {
     if(Input.GetKeyDown(E);
          isEpressed = true;
     }
     
     //write this is onTriggerEnter2d
     if(isEpressed)
     {
     //ur  above code 
     }

avatar image TheIrishKraken prakyathd801 · Jan 03, 2021 at 07:01 AM 0
Share

Thanks for the reply but that approach didn't work. if(isEpressed) gets completely ignored inside the OnTriggerEnter2D() method. $$anonymous$$aybe you cant do any other checks inside that method except checking for collision.

avatar image
0

Answer by Llama_w_2Ls · Jan 02, 2021 at 08:00 AM

You should do a raycast in the Update() to see which enemy you're closest to, by getting the distance from each enemy to the player and sorting it. This could be done every time you press the 'E' key, and if the distance between an enemy and the player is very small, you're colliding. @TheIrishKraken

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.

Follow this Question

Answers Answers and Comments

148 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

Related Questions

trigger problem 0 Answers

2D Character slows down in a trigger 2 Answers

How to activate all GameObjects named ,,GroundCollider'' by touching ,,GroundTriggerCollider'' and deactivating when no longer touching ''GroundCollider"? 1 Answer

Trigger in child - boxcollider2d without trigger on parent issues. 0 Answers

Have GUI element enter screen on trigger 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