Hi guys im new to unity , i was trying to make my player getting damaged through collider OnTriggerEnter after looking on the internet this what i got, but i dont know why its still not working , i have checkd the istrigger on enemy collider2d , please help me .
This is my EnemyAttack script :
public class EnemyAttack : MonoBehaviour
{
public float enemyCooldown = 1;
public int damage = 10;
private bool playerInRange = false;
private bool canAttack = true;
private void Update()
{
if (playerInRange && canAttack)
{
GameObject.Find(“Player”).GetComponent().currentHealth -= damage;
StartCoroutine(AttackCooldown());
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag(“Player”))
{
playerInRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag(“Player”))
{
playerInRange = false;
}
}
IEnumerator AttackCooldown()
{
canAttack = false;
yield return new WaitForSeconds(enemyCooldown);
canAttack = true;
}
}
and this is the PlayerHealth script :
public int maxHealth = 100;
public int currentHealth;
public Healthbar healthBar;
public GameObject deathEffect;
public void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
if (currentHealth <= 0)
{
Die();
}
}
void Die()
{
//Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
can you use Debug.Log() to see wether playerInRange or canAttack are false in the update method
can you do the same to see wether OnTriggerEnter is ever called?
2 oddities I have noticed:
you use OnTriggerEnter and OnTriggerExit, but you posted this in the 2D forum…
if you are using 2DColliders you need to use the functions OnTriggerEnter2D and OnTriggerExit2D
the normal Trigger functions wont register 2D collider
this isnt related to your problem, but I have noticed that you defined a “TakeDamage” function, yet you still directly alter the health in the enemy by currentHealth -= damage, I assume you wanted to call here TakeDamage instead
furthermore if the Trigger functions never execute (check this by using Debug.Log), even after you made sure you used the right functions for your collider (2D functions for 2D collider), make sure your setup follows this instruction from Unity - Scripting API: Collider.OnTriggerEnter(Collider)
“Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.”