- Home /
Null Reference Exception on Raycast
var fireSound : AudioClip;
var reloadSound : AudioClip;
var bullets : float;
var reloadTimer : float;
var coolTimer : float;
function Start () {
}
function Update () {
if (coolTimer) {
coolTimer -= Time.deltaTime;
if (coolTimer < 0) {
coolTimer = 0;
}
}
if (reloadTimer) {
reloadTimer -= Time.deltaTime;
if (reloadTimer < 0) {
reloadTimer = 0;
}
}
if (!bullets) {
audio.PlayOneShot(reloadSound);
reloadTimer = 3.0;
bullets = 30;
}
if (bullets && !coolTimer && !reloadTimer) {
audio.PlayOneShot(fireSound);
coolTimer = 0.1;
bullets -= 1;
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward) * 1000)) {
if (hit.collider.name == "Character") {
Health.health -= 1;
}
}
}
}
This script controls the enemy weapon. Everytime I stand in front of the thing, it gives me an error message saying "Object reference not set to an instance of an object". This is not the first time I've had this show up. What is it and how do I fix the issue?
Answer by rutter · Nov 03, 2012 at 02:16 AM
We can be a little bit more helpful if you point out the exact line that's throwing the exception.
I'm guessing that it's this one:
if (hit.collider.name == "Character") {
I say that because your raycast call doesn't look like it will populate the `hit` variable:
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward) * 1000)) {
There are many different versions of `Physics.Raycast()`, each of which has slightly different properties. You might try calling one of the versions which takes a `RaycastHit` parameter, perhaps like this:
Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), hit, 1000)
@ alucardj I'd like to give credit to you for posting the original answer. I misunderstood. Thanks for the help man
no worries, am happy you found out and understood in your own way. Happy Coding =]
Answer by mbhaworth · Nov 03, 2012 at 08:30 AM
Look at your use of Physics.Raycast. As far as I can tell the variable hit is never set.
Your answer
Follow this Question
Related Questions
"Object reference not set to an instance of an object" Error 1 Answer
What is wrong with my script? 1 Answer
BCE0044 Error - expecting :, found '=' 0 Answers
NullReferenceException array 2 Answers