Hi everyone, I’m new to C# and new to Unity as well so I hope you guys can be lenient and tolerate me for my questions.
I am trying to script a “DamageController” where if an enemy fires a prefab and triggers the CircleCollider2D, it reduces my player’s health.
void OnTriggerEnter2D() {
GetComponent<Animator>().SetTrigger(Animation_Is_Damage);
//DAMAGE CALCULATION TO PLAYER FOR AD1
if (gameObject.tag == "AD1") {
playerHealth -= 2;
if (playerHealth <= 0) {
Destroy(gameObject);
}
}
}
I know for sure that my colliders are working as it successfully played my “Is_Damage” animation but not for the playerHealth part.
I had researched on gameObject.Tag, CompareTag, FindTagWith but to no avail. Or perhaps maybe I’m using it all wrong because like I’ve said, I’m pretty new to everything. I hope someone can shed some light! Thank you all in advance gentlemen!
Am i correct in assuming this script in on the player? When anything collides with the player this script is run from the player itself? I would expect the tag you should be checking for is the bullet tag, not the players since you are already on the players script.
I agree with absolute_disgrace, you should be checking for the bullet tag. You are currently checking the player tag. I think that you’d need to set the animation trigger in the if block too since you might have different triggers in your level that could unintentionally trigger the damage animation. So you’d need to change the code to something like this:
void OnTriggerEnter2D(Collider2D other) {
//DAMAGE CALCULATION TO PLAYER FOR AD1
if (other.gameObject.tag == "AD1") {
GetComponent<Animator>().SetTrigger(Animation_Is_Damage);
playerHealth -= 2;
if (playerHealth <= 0) {
Destroy(gameObject);
}
}
}
All of this is going on the assumption that you attached the script to the player.
As a side note: the print method is very handy to debug these situations. You could add in the following code to show what is tag triggered the callback.
print("the tag is " + other.gameObject.tag);