Raycast does not working en my proyect

Hello people, I would like to thank you for the help.

I have a problem with Raycast, the code works well in another scene, but in which I need it I get an error.
NullReferenceException: Object reference not set to an instance of an object
RayCast.Update ()

I have deactivated everything, to see that they do not affect the scripts, in the RayCast script execution.

I want to know what happens, I do not understand why it does not work.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class RayCast : MonoBehaviour {

    public LayerMask ClickLayer;
    // Use this for initialization
    void Start () {
       
    }

    // Update is called once per frame
    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            RaycastHit hitInfo;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hitInfo, 100.0f, ClickLayer))
            {
                Debug.Log(hitInfo.collider.name);
            }
        }

    }
}

regards

You should tag your camera properly. Also it worth to cache the reference to the Camera.main like in the example on the page I linked above.

2 Likes

Good devs are lazy devs.

Unity has already provided the “raycast into scene to detect if a object is clicked” functionality through the EventSystem and PhysicsRaycaster components. There is little value to recreating this yourself. Just add the appropriate components to the scene. You can get callbacks via the IPointerClick interface, an Event Trigger component, or by calling EventSystem.Raycast yourself.

Be more lazy!

3 Likes

LurkingNinjaDev**
How crazy, I did not see it … well, thank you very much
Sorry for the inconvenience.
And Kiwasi, thanks for the advice.
**

Happens with the best of us. And after a while it becomes one of the first things you’re looking for… :slight_smile:

1 Like