- Home /
OnTriggerEnter not working properly in if satetment
void onTriggerEnter (Collider col)
{
if (col.gameObject == enemy)
{
enemyInRange = true;
}
}
void onTriggerExit (Collider col)
{
if (col.gameObject == enemy)
{
enemyInRange = false;
}
}
void Update () { // this is my update func.
timer += Time.deltaTime;
if (timer >= timebetweenattack && enemyInRange ) { //This is where i get wrong, when i remove "enemyinrange" in if statement, i can damage enemy but even if the enemy is out of range.
if (Input.GetMouseButton (0)) {
Melee ();
}
}
}
void Melee() { timer = 0f;
if(enemyHealth.currentHealth > 0)
{
// ... damage the player.
enemyHealth.TakeDamage (attackDam);
}
}
}
Ensure that the object you are colliding with is set to an Trigger. You can do that by selecting it from its collider behavior in the inspector
Answer by Cornelis-de-Jager · Aug 08, 2017 at 10:48 PM
Try the following:
If your target is not set to an Trigger do that.
Use a Tag instead
if (col.tag == "enemy") // Have to set the tags however { enemyInRange = true; }
i already did that. not working. if i remove enemyinrange in my if statement, it is working properly. but as i said i want to damage enemy if it is inside my sphere collider
Answer by bobisgod234 · Aug 09, 2017 at 06:45 AM
Its OnTriggerEnter and OnTriggerExit, not onTriggerEnter and onTriggerExit. Note the capital O's
What is 'enemy'? How are you assigning it? I suspect you may have assigned the enemy prefab to it. The enemy prefab won't compare true to any instance in the scene. I would use Cornelis-de-Jager's suggestion and use tags. Make sure you have actually set the enemy's gameobject with the collider to have an "enemy" tag.
Also try adding Debug.Log statements to see where the problem is, like this:
void OnTriggerEnter (Collider col)
{
Debug.Log("Entered trigger " + col.gameObject + " are they equal? " + (col.gameObject == enemy);
if (col.gameObject == enemy)
{
enemyInRange = true;
}
}
Also, your code will have an issue where if two enemies get in range, and one leaves, your code will incorrectly think that no enemies are in range. Try maintaining a count of enemies instead. change enemyInRange to an int, and replace "enemyInRange = true;" with "enemyInRange++;" and "enemyInRange = false;" with "enemyInRange--;".
Your answer