I’m trying to hit an item with a raycast and then use the SendMessageUpwards function to subtract from that items health but I keep getting the “Object reference is not set to an instance of an object” error. Here is the code with the raycast
var shootAudio : AudioClip ;
var damage = 100;
var Range = 10.0;
function Start () {
}
function Update () {
if(Input.GetButtonDown("Shoot/Attack")){
Shoot();
}
}
function Shoot(){
var hit : RaycastHit;
var collider : Collider;
Debug.DrawRay(transform.position, transform.forward*Range, Color.green);
audio.PlayOneShot( shootAudio);
if(Physics.Raycast(transform.position, transform.forward, Range)){
hit.collider.SendMessageUpwards("ApplyDamage" , damage , SendMessageOptions.DontRequireReceiver);
}
}
Here is the health script
var healthLeft = 100;
function Start () {
}
function Update () {
if(healthLeft <= 0){
Destroy(gameObject);
}
}
function ApplyDamage( damage : int ) {
healthLeft -= damage;
}