Question by
Swordfish12 · Jun 01, 2016 at 04:59 PM ·
raycastnullreferenceexceptionhealth
Null reference exception object reference not set in an instance of an object
I have 2 scripts one is a raycast script and one is a health script my error comes in on the raycast script on the code where i fire a raycast and access the void apply damage.
Health
public class HealthBear : MonoBehaviour {
public int health = 200;
private bool isDead = false;
public GameObject animal;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
public void ApplyDamage (int amount)
{
if (isDead)
return;
health -= amount;
if (health <= 0)
{
Death ();
}
}
public void Death ()
{
isDead = true;
Destroy (animal, 3f);
}
}
Raycast
using UnityEngine;
using System.Collections;
public class Raycast : MonoBehaviour
{
public float range;
private RaycastHit hit;
private Transform myTransform;
public float nextFire;
public float fireRate = 0.3f;
public HealthBear healthBear;
public int damage;
void Start ()
{
SetInitialreferences ();
}
void SetInitialreferences ()
{
myTransform = transform;
}
void FixedUpdate ()
{
CheckForInput ();
}
void CheckForInput ()
{
if (Input.GetButton("Fire1") && Time.time>nextFire)
{
Debug.DrawRay (myTransform.TransformPoint(0,0,1), myTransform.forward, Color.red, 3);
if(Physics.Raycast(myTransform.position, myTransform.forward, out hit, range))
{
Debug.Log (hit.transform.name);
healthBear.ApplyDamage (damage);
}
nextFire = Time.time+fireRate;
}
}
public void ApplyDamage (float damage)
{
}
}
Comment
Answer by Static-Dynamo · Jun 01, 2016 at 11:37 PM
Have you properly plugged in the object that is "healthBear" in your inspector? If you haven't then it can't find it and that's why it's throwing an exception, because healthBear is null. You never assign it in your script so you have to make sure it's plugged in manually in the inspector.
Also it's strange that you have a call for healthBear.ApplyDamage, yet in your ray cast script you also have ApplyDamage. Is the raycast script also going to be on your healthBear gameobject?
Your answer
