I am creating a VR mouse to avoid the issues that the Oculus integration has with a standard mouse. However for some reason I am getting a Null Reference Exception where I am referencing my other script. I have tested VRmouse, hovHit and hovHit.collider.tag to see if any of them are null - none of them are. Every object I reference in the script exists in my scene. The code works but I would prefer to not get a Null Reference. Here is the script, if you would like the other script I can send it.
using UnityEngine;
using System.Collections;
public class UI_MouseHoverAnim : MonoBehaviour
{
public bool mouseOver;
private GameObject VRmouse;
private RaycastHit hovHit;
private Animator anim;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator> ();
VRmouse = GameObject.FindGameObjectWithTag ("vrMouse");
hovHit = VRmouse.GetComponent<VRmouse> ().hoverHit;
}
// Update is called once per frame
void Update ()
{
if (hovHit.collider.tag == "ArchiveModel"){
anim.SetBool ("mouseOver", true);
} else {
anim.SetBool ("mouseOver", false);
}
}
}
Please help, cannot figure this out despite doing a lot of reading on Null Reference.
Which line gives the error?
1 Like
So I changed line 25 from VRmouse.GetComponent<VRmouse> ().hoverHit.collider.tag to what it is in the code above which actually stopped it from functioning (still get null reference). But line 25 is where I am getting the error.
Well there’s a couple of issues - one, and most obviously, it seems likely that collider is null. You can test that:
if(hovHit.collider == null)
Debug.Log("Collider is null");
Secondly, RaycastHit is a struct not a class, so copying the value in Awake() isn’t going to do much of anything if you’re trying to poll the result of a raycast from another component.
The only reason I put the RaycastHit hovHit into this script was because I just wanted to write the code differently to see if it changed anything.
It would seem you are correct about the collider being null though. How do I fix this? Because the object I am interacting with has a collider on it.
RaycastHit’s collider is only set when the raycast actually hits something. It seems very unlikely that you’re hitting anything in another component’s Awake() function.
Ok, I will check RaycastHit’s collider in my other script to see if it is null there. Would it be helpful for me to post the VRmouse script i am referencing?
Ok now I’m stumped on what to do. The script is functioning correctly, when my mouse is hovering over the object with that tag the null references stop. Any ideas on how to approach this issue?
Check for null before you test the tag?
if(whatever.collider != null && whatever.collider.tag == "what you want")
Had a feeling. Thanks so much for your help! Much appreciated.
1 Like