Search Unity

How to make OnTriggerEnter2D work again upon the GameObject being disabled and then re-enabled?

Discussion in '2D' started by Slayer3201, Feb 14, 2017.

  1. Slayer3201

    Slayer3201

    Joined:
    Aug 27, 2016
    Posts:
    5
    In the game I'm working on, I am noticing something strange that I do not want to happen. Whenever I have the player attack what is infront of them, it only works once. If the enemy stands still, and the player stands still while attacking, the player can not harm the enemy after the first swing. Either the enemy or the player has to move again in order for the attack to actually inflict damage upon said enemy. What I want to know is how to fix this, so I can have both the player and enemy stand still and still be able to inflict damage upon one-another.

    What I have for an "attack" is simple. The player approaches the enemy, clicks, and that stops the player's movement while the attack animation plays, which enables an object that is a child object of the Player, with this object specifically being a slash effect. This object has a trigger attached to it, which activates on any enemy it touches, supposedly. The slash also has a script attached to it which does the actual harming, said script being called "HurtEnemy", which can be seen here:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class HurtEnemy : MonoBehaviour {
    5.  
    6.     private int damageToDeal;
    7.     public Transform hitPoint;
    8.     public GameObject damageNumber;
    9.  
    10.     private bool justCrit;
    11.     private int baseDamage;
    12.     public int critChance;
    13.  
    14.     private PlayerStats pATK;
    15.  
    16.     void Start () {
    17.         pATK = FindObjectOfType<PlayerStats> ();
    18.         damageToDeal = 0;
    19.         baseDamage = 0;
    20.     }
    21.  
    22.     void Update () {
    23.      
    24.     }
    25.  
    26.     void OnTriggerEnter2D(Collider2D other) {
    27.         if (other.gameObject.tag == "Enemy") {
    28.             baseDamage = pATK.currentATK;
    29.             damageToDeal = baseDamage;
    30.  
    31.             damageToDeal += Random.Range (-1, 2); //Adds a bit of randomness to damage dealt.
    32.  
    33.             if (Random.Range (1, 100) <= critChance) { //Possibility of crit, exact chance able to be changed via Unity interface.
    34.                 damageToDeal *= 2;
    35.                 justCrit = true;
    36.             }
    37.  
    38.             other.gameObject.GetComponent<EnemyHealthManager> ().HurtEnemy (damageToDeal);
    39.  
    40.             var clone = (GameObject)Instantiate (damageNumber, hitPoint.position, Quaternion.Euler (Vector3.zero));
    41.  
    42.             if (justCrit) {
    43.                 clone.GetComponent<FloatingNumbers> ().damageNumber = damageToDeal;
    44.                 clone.GetComponent<FloatingNumbers> ().displayNumber.color = Color.yellow;
    45.                 justCrit = false;
    46.             } else {
    47.                 clone.GetComponent<FloatingNumbers> ().damageNumber = damageToDeal;
    48.                 clone.GetComponent<FloatingNumbers> ().displayNumber.color = Color.white;
    49.             }
    50.  
    51.             damageToDeal = baseDamage;
    52.         } else if (other.gameObject.tag == "Destructable") {
    53.             other.gameObject.GetComponent<DestructableObjectManager> ().KillObject ();
    54.         }
    55.     }
    56. }
    The actual damage is dealt when this script calls another script on the object it touches, called "EnemyHealthManager", specifically a "HurtEnemy" function. The script in question can be seen here:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyHealthManager : MonoBehaviour {
    5.  
    6.     public int enemyMaxHealth;
    7.     public int enemyCurrentHealth;
    8.  
    9.     private PlayerStats thePlayer;
    10.  
    11.     public int expUponDeath;
    12.  
    13.     void Start () {
    14.         enemyCurrentHealth = enemyMaxHealth;
    15.  
    16.         thePlayer = FindObjectOfType<PlayerStats> ();
    17.     }
    18.  
    19.     void Update () {
    20.         if (enemyCurrentHealth <= 0) {
    21.             thePlayer.AddExperience (expUponDeath);
    22.             Destroy (gameObject);
    23.         }
    24.     }
    25.  
    26.     public void HurtEnemy(int damage) {
    27.         enemyCurrentHealth -= damage;
    28.         StartCoroutine ("HurtColor");
    29.     }
    30.  
    31.     public void MaxHealth() {
    32.         enemyCurrentHealth = enemyMaxHealth;
    33.     }
    34.  
    35.     IEnumerator HurtColor() {
    36.         for (int i = 0; i < 3; i++) {
    37.             GetComponent<SpriteRenderer>().color = new Color (0.8f, 0.6f, 0.8f);
    38.             yield return new WaitForSeconds (.1f);
    39.             GetComponent<SpriteRenderer>().color = Color.white;
    40.             yield return new WaitForSeconds (.1f);
    41.         }
    42.     }
    43. }
    This health manager deals with the enemy's, well, health. Once the enemy's HP reaches zero, the gameobject of said enemy is completely destroyed, and the player given a set amount of experience.

    With all that out of the way, it sounds like everything should be perfectly fine, right? I'd think so. Except for the one issue that is still bugging me non-stop, the OnTriggerEnter2D on the slash object (the one with the "HurtEnemy" script) does not activate a second time, even once the slash object's active variable is turned on and then off. How can I make it so everytime the player attacks, the OnTriggerEnter2D works again upon the slash being re-enabled?
     
  2. jackhearts

    jackhearts

    Joined:
    Apr 5, 2013
    Posts:
    103
    Put a debug line in OnTriggerExit2D to check it is actually firing. If the two colliders are close enough without movement you may find Exit isn't being called which then prevents Enter firing again.
     
  3. Slayer3201

    Slayer3201

    Joined:
    Aug 27, 2016
    Posts:
    5
    Alright, I'll try that when I can, but what if that's why Enter is being prevented from firing? What can I do then to fix it? Any suggestions/ideas?
     
  4. jackhearts

    jackhearts

    Joined:
    Apr 5, 2013
    Posts:
    103
    Depends on how your characters are set up. You need to guarantee the collider is leaving the enemy collider after each attack. Try pausing once you've hit attack and stepping through each frame in scene view to check.

    Alternatively you could disable the collider after each hit and only enable when the attack button is pressed.

    In the HurtEnemy script put this as the last line of code within OnTriggerEnter2D. Adapt it to however your objects are set up. It will disable the collider after your hit code has run.
    Code (CSharp):
    1.             gameObject.GetComponent<BoxCollider2D>().enabled = false;
    2.  
    You'll also need to enable it immediately after the attack button is pressed. So use the same line of code and chance false to true. Probably easier to set a public reference to the collider and use that in the scripts.
     
    Last edited: Feb 15, 2017
  5. Slayer3201

    Slayer3201

    Joined:
    Aug 27, 2016
    Posts:
    5
    The issue is that in order for the attack collider to exit the enemy collider, either the enemy or the player have to move. So your first suggestion is practically impossible with how I have it set up. With your secondary suggestion, I just tried that, but that does not work either. Simply turning the collider off and then back on does not re-run the OnTriggerEnter2D section of the code, which is what I need to happen whenever the player attacks again.

    Also, I did that debug idea from your very first suggestion, and OnTriggerExit2D is not firing, again, unless the player moves away. I'm beginning to think that the issue here is that I need to find a replacement for the OnTriggerEnter idea.
     
    Last edited: Feb 16, 2017
  6. jackhearts

    jackhearts

    Joined:
    Apr 5, 2013
    Posts:
    103
    I don't know how the attack works but if it's a slash effect is the collider in any kind of motion? If it is could you alter it in some way so that it will always clear the enemy by retracting back or overshooting?

    Disabling and enabling a collider that's overlapping a trigger should run OnTriggerEnter2D each time it's enabled. Or at least it does for me. Do you see the collider become unticked in the inspector after a hit and then ticked again on the next hit command?

    You've got OnTriggerStay2D that you could use to manage a hit counter.
     
  7. Slayer3201

    Slayer3201

    Joined:
    Aug 27, 2016
    Posts:
    5
    Let me tell you how the attack works exactly then. In my PlayerController script, I have the attack set up there. Upon clicking, it changes a variable in the animator as well as some other magic, which then causes the player to stop all motion and do the attack animation, which enables the slash game object, which has the HurtEnemy script attached. At the end of the animation, the game object of said slash is turned back off, and it only is enabled again upon the next attack.

    You meant disabling the enemy collider? I thought you meant disabling the trigger. My bad. That might work, I'll have to simply add some code and a timer to have the enemy collider do that though. However, I do see one downside to that. What if another enemy comes up to the player while the enemy collider is disabled? Will the enemy just phase through the enemy being attacked? How would I be able to stop that if the 1st enemy's collider is disabled? Regardless, I'll try that when I can.

    OnTriggerStay2D could also work, I'd just have to set up an invincibility frames system. I haven't had the best of luck with that in the past, but it's not a bad idea. Again, I could try that though. I'll give you the results when I can try it, which will probably be sometime the day after this reply was sent.
     
    Last edited: Feb 17, 2017
  8. Slayer3201

    Slayer3201

    Joined:
    Aug 27, 2016
    Posts:
    5
    Sadly, I've tried both things now, neither still work for me. I guess I'll just continue on with my game and completely revamp the player attack system later or something. :/
     
  9. jackhearts

    jackhearts

    Joined:
    Apr 5, 2013
    Posts:
    103
    I did mean disable your slash trigger collider. A game object with a trigger collider and script attached listening for triggers should run OnTriggerEnter each time that objects collider is enabled even if already overlapping. So the script attached to your slash object could disable the slash collider after the hit code runs and enable the collider when the player clicks attack.

    There's always a variety of ways to achieve the same result. You might find it more reliable to use Ray2D for checking an enemy is within range instead of a trigger. Something like
    1. player hits attack
    2. run animation
    3. ray cast to check enemy within range
    4. if in range deal damage