Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 SwinMichael · Jun 14, 2020 at 02:05 PM · collision detectioncollision2dmultiple objects

OnCollisionEnter2D and OnCollisionExit2D executed at the same time

Hi, I'm doing a simple 2D Side Scrolling Tower Defense Game. I'm facing this issue where both OnCollisionEnter2D and OnCollisionExit2D are called at the same time, hence make the code inside both of them cancelling out each other. Everything works well if just one of my object (with this script on it) is colliding with just another one object (which has the BoxCollider2D). But the problem starts to come when there is a second object (with this script) starts coming in (stacking) and the OnCollisionEnter2D and OnCollisionExit2D will start to both be executed at the same time.

I'm very very new to Unity as well as codings, so please do go easy on me. Any help would be much appreciated!

The full scripts are as follow :

 using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class FriendlyKnightUnits : MonoBehaviour
  {
      // Components
      private Animator anim;
      private Rigidbody2D rb;
      private Collider2D coll;
  
      // FSM
      private enum State { walk, attack, death };
      private State state = State.walk;
  
      // Inspector Variables
      private float walkSpeed;
      [SerializeField] private float initialWalkSpeed = 1.1f;
  
      // Start Variables
      private Vector2 unitPosition;
  
      // Health variables
      public int maxHealth = 120;
      private int currentHealth;
      public HealthBar healthBar;
  
      public int attackDamage = 20;
  
      public Transform attackPoint;
      public float attackRange = 0.5f;
      public LayerMask enemyLayers;
  
      // Sound Variables
      private AudioSource soundSource;
      [SerializeField] private AudioClip swordSwing;
  
      void Start()
      {
          currentHealth = maxHealth;
          healthBar.SetMaxHealth(maxHealth);
  
          walkSpeed = initialWalkSpeed;
  
          anim = GetComponent<Animator>();
          rb = GetComponent<Rigidbody2D>();
          coll = GetComponent<Collider2D>();
          soundSource = GetComponent<AudioSource>();
      }
  
      void Update()
      {
          anim.SetInteger("state", (int)state);
  
          rb.velocity = new Vector2(walkSpeed, rb.velocity.y);
      }
  
      private void OnCollisionEnter2D(Collision2D collision)
      {
          if (collision.gameObject.CompareTag("Enemy"))
          {
              state = State.attack;
              walkSpeed = 0;
          }
  
          if (collision.gameObject.CompareTag("Player"))
          {
              Physics2D.IgnoreCollision(coll, collision.transform.GetComponent<Collider2D>());
          }
      }
  
      private void OnTriggerEnter2D(Collider2D collide)
      {
          if (collide.gameObject.name == "EnemyCastle")
          {
              state = State.attack;
              walkSpeed = 0;
          }
      }
  
      private void OnCollisionExit2D(Collision2D collision)
      {
          if (collision.gameObject.CompareTag("Enemy"))
          {
              walkSpeed = initialWalkSpeed;
              state = State.walk;
          }
      }
  
      void Attack()
      {
          // Detect enemies in range of attack
          Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
  
          // Damage them
          foreach (Collider2D enemy in hitEnemies)
          {
              if (enemy.GetComponent<EnemyKnightUnits>())
              {
                  enemy.GetComponent<EnemyKnightUnits>().TakeDamage(attackDamage);
              }
  
              if (enemy.GetComponent<EnemyMinerUnits>())
              {
                  enemy.GetComponent<EnemyMinerUnits>().TakeDamage(attackDamage);
              }
          }
      }
  
      private void OnDrawGizmosSelected()
      {
          if (attackPoint == null)
          {
              return;
          }
  
          Gizmos.color = Color.red;
          Gizmos.DrawWireSphere(attackPoint.position, attackRange);
      }
  
      public void TakeDamage(int damage)
      {
          currentHealth -= damage;
  
          // Set the health slider
          healthBar.SetHealth(currentHealth);
  
          if (currentHealth <= 0)
          {
              Die();
          }
      }
  
      void Die()
      {
          // Die animation
          anim.SetInteger("state", (int)State.death);
  
          // Disable your unit
          rb.gravityScale = 0f;
          coll.enabled = false;
          this.enabled = false;
          Destroy(this.gameObject, 3f);
      }
  
      private void SwordSwing()
      {
          soundSource.clip = swordSwing;
          soundSource.Play();
          Attack();
      }
  }

I'm starting to suspect that the issue might be caused from these lines of scripts at line 65 - 70, but I couldn't be sure.

 if (collision.gameObject.CompareTag("Player"))
          {
              Physics2D.IgnoreCollision(coll, collision.transform.GetComponent<Collider2D>());
          }

I need this part of the code to be in my script because I want my object to be able to stack on each other.

Comment
Add comment · Show 2
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 SwinMichael · Jun 15, 2020 at 02:04 AM 0
Share

@ShadyProductions Hi, can I get help about my issue? or is anyone able to help with this? I'm a little stuck at my game here. Need urgent help.

avatar image ShadyProductions · Jun 15, 2020 at 06:43 AM 0
Share

So what I'm understanding of this is that you don't want the player to collide with it. Why don't you just add a collision layer to both player and the other object and disable collision between them in the collision matrix, that way you won't need Physics2D.IgnoreCollision

0 Replies

· Add your reply
  • Sort: 

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

131 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

Related Questions

2d Collision not detect player when it falls 2 Answers

if statement not working when detecting collision between two prefabs 1 Answer

2D Collider seems bigger than it is 1 Answer

collisions does not get detected every time 0 Answers

Collision 2D doesnt work 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