[SOLVED]NullReferenceException on a Collider

Hi all,

I am getting a NullReferenceException and would like to nip it in the bud.

I have a Script that shoots a ray and finds the collider:

// Update is called once per frame
	void Update () {
	    
	    vec.x = (float)Screen.width / 2;
	    vec.y = (float)Screen.height / 2;
	    vec.z = 0;
        
        ray = camera.ScreenPointToRay(vec);

        // Only look in Layer 8 (Level Assets)
        layerMask = 1 << 8;

        if (Physics.Raycast(ray, out hit, 10.0f, layerMask))
        {
            collider1 = hit.collider;
            Debug.Log(collider1.name);
        }
	}

And a Script that handles the object colour and ‘picking’ if the ray hits it:

// Update is called once per frame
	void Update () {

        // Pass all Variable to the Unity Editor
	    FlashLight = PlayerFLight;
 
        // Check FlashLight Collider
        if (CameraRayCasting.collider1.name.Equals("FlashLight"))
        {
            // Change colour of object (rollover)
            GameObject.Find("FlashLight").renderer.material.color = Color.red;

            // Check for 'E'Key - Picking up the Flashlight
            if (Input.GetKeyDown(KeyCode.E))
            {
                // We now have a FlashLight
                PlayerFLight = true;

                //Turn on the Flashlight
                SpotLight.LightState = true;

                //Remove Flashlight GameObject from world
                GameObject.Find("FlashLight").active = false;
            }
        }
        else if (!CameraRayCasting.collider1.name.Equals("FlashLight")  !PlayerFLight)
        {
            GameObject.Find("FlashLight").renderer.material.color = Color.white;
        }
     }

As I am only checking for objects within a certain Layer, the collider is NULL until it hits one. As soon as this happen the Null exception goes away.

Is there away to stop this and check for the collider being null? (BTW, the collider is a public static)

Matt.

add a

if( CameraRayCasting.collider1 == NULL )
  return;

before the whole inner codeblock on the second function. Otherwise you try to access a variable thats null and that just has no way to talk to you other than throwing exceptions against your head till you hopefully realize that you shouldn’t be accessing it at that time :wink:

Many thanks dreamora, my head is relieved.

Matt.