NullReferenceException: Object reference not set to an instance of an object?

This code work

function EnemyDmg(){
		
		var hit : RaycastHit;
		if (Physics.Raycast(transform.position, transform.forward, hit, EnemyRange)){
		
				GameObject.Find("Soldier").GetComponent(health).TakeDmg(EnemyDamage);
				
		}
}

Why if i use hit.collider doesn’t works?

function EnemyDmg(){
		
		var hit : RaycastHit;
		if (Physics.Raycast(transform.position, transform.forward, hit, EnemyRange)){
		
				hit.collider.gameObject.GetComponent(health).TakeDmg(EnemyDamage);
				
		}
}

Unity report me the following warning "NullReferenceException: Object reference not set to an instance of an object
AI.EnemyDmg () (at Assets/Script/AI.js:40)
"

My guess is that your raycast is not hitting the correct gameObject.

Try

health = hit.collider.gameObject.GetComponent(health);
if(health){
    health.TakeDmg(EnemyDamage);
}

You could also use Debug.DrayRay to figure out what the ray is actually hitting.