- Home /
Question by
Superivan94 · Jun 15, 2014 at 07:40 PM ·
null reference exception
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) "
Comment
Answer by Kiwasi · Jun 15, 2014 at 07:47 PM
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.
Your answer
