- Home /
Why won't my Ray initialization work??
I am using a Raycast from my mouse position to select an object in 3d space but my code is coming up with error NullReferenceException: Object reference not set to an instance of an object CameraControl.CameraSelect () (at Assets/Scripts/CameraControl.cs:32)
here is my code
void CameraSelect() {
RaycastHit rayHit;
if(Input.GetButton("Fire1")){
Debug.Log(curCam);
Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out rayHit,9999)){
curCam.enabled = false;
tarCam = rayHit.transform.gameObject.GetComponentInChildren< Camera >();
tarCam.enabled = true;
}
}
}
it seems that my ray initialization is giving me the error, that is line 32, but from what i can tell my code is correct? please help
the error is on line 5 of the code snippet
Answer by GameVortex · Jan 27, 2014 at 09:00 AM
Your Ray initialization itself is correct.
The problem comes from the use of Camera.current which only has a value in the OnRenderImage, OnPreRender and OnPostRender events, because it references the currently rendering camera. Outside of those events you would want to use Camera.main instead (referencing the camera tagged "MainCamera"), or reference the camera you want to use yourself through a public camera variable.
Well I need to reference the current camera being displayed, I have a public variable that holds the current camera named curCam, could I use Camera.curCam.ScreenPointToRay?
If you have a public variable curCam in the same class as the CameraSelect function you can use it directly: curCam.ScreenPointToRay.
Alright I'll try that and I'll post when I get home. Thanks for your help!
Answer by Shrikky23 · Jan 27, 2014 at 06:24 AM
Hi this is how you create a ray public Ray ray = new Ray(transform.position, transform.forward);
So in your case public Ray ray = new Ray(Input.mousePosition , target position);
i dont know the target position though, im just trying to see if there is an object where i clicked and if so then to switch the current camera to the objects child camera