Null reference error when using raycast hit to get component

    private void Update()

    {
        RaycastHit hit;
        Ray ray = new Ray(transform.position, Vector3.down);

        if (Input.GetMouseButton(1))

        {
            if (Physics.Raycast(ray, out hit, 1000))

            {
                    woodMiracleParticles.SetActive(true);
                    currentWood =- 1;
                    WorkshopScript workshopScript = hit.transform.gameObject.GetComponent<WorkshopScript>();
                    workshopScript.IncreaseWorkshopWood();
            }
        }

By all accounts this code should work fine so I’m pretty confused about what I’ve done wrong here, as you can see I’m using a raycast to grab the component of the gameobject it hits but despite the fact that I’ve gotten the workshop script without any errors the moment I try to make the script do anything then it complains.

It’s probably going to be one of those things that’s really obvious when I have it explained to me.

workshopScript.IncreaseWorkshopWood();

Is where the error points to, by the way, the script is definitely on the object the raycast is hitting so there should be no problems there.

Obviously it is not, other way it would be returned by GetComponent call. Null return means there’s no script of such type on that game object. Probably, something is messing in the way. Try to Debug.Log name of the gameobject hit by raycast and check if expectation meets the reality.

1 Like

lol thanks @palex-nx I just immediately fixed it, it turned out that there was one gameobject that I forgot to disable which had a collider and that was causing all of the problems -_- I’ll need to keep that debug log code in mind in the future if I have annoyances going on with raycasting again.

Debug.Log(hit.transform.gameObject);

This is what I used to debug, something to bare in mind which threw me off when using it you have to put the Debug.Log for the raycast before all your other code otherwise it will just throw up errors as normal because the error won’t allow the Debug.Log to execute.

Yep, all working correctly now.

When messing with raycasts, it’s better to always assume there anything might accidentally get inbetween source and expected target. There are two options to help dealing with such things. A version of raycast wich returns an array or fills a list of objects along the ray and layer filtering. Using those makes raycast systems much more accurate and performant.

1 Like