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);
	}
}

}

Try the following:

  1. If your target is not set to an Trigger do that.

  2. Use a Tag instead

    if (col.tag == "enemy") // Have to set the tags however
    {
      enemyInRange = true;
    }
    

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–;”.