Why is this coming up null???

NullReferenceException: Object reference not set to an instance of an object
Grab.Update () (at Assets/Grab.cs:25)

I’m not getting why I’m getting told this is coming up null, I just gave “grabMe” a value!

        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, reach, layerMask))
        {
            GameObject item = hit.transform.gameObject;
            GrabMe grabMe = item.GetComponent<GrabMe>();
            grabMe.highLighted = true;
        }

After line 4, print the name of the GameObject it finds.

Debug.Log( item.name);

Make sure it’s what you expect, i.e, where the GrabMe is located.

2 Likes

Probably because the hit object ‘item’ does not have a GrabMe component on it.

3 Likes

Ah, I’m thinking I’m having an LOD issue then.

I attached the script to my LOD0.

You could make a proxy common collider object just for this “hey you can grab me!” indicator… that way you don’t have to clone it to all the LODs…

1 Like

FPSController
UnityEngine.Debug:Log(Object)
Grab:Update() (at Assets/Grab.cs:24)

Maybe it’s my masking?

.Here’s the entire code:

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

public class Grab : MonoBehaviour
{
    public float reach;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        int layerMask = 1 << 8;
        layerMask = ~layerMask;
       
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, reach, layerMask))
        {
            GameObject item = hit.transform.gameObject;
            Debug.Log(item.name);
            GrabMe grabMe = item.GetComponent<GrabMe>();
            grabMe.highLighted = true;
        }
    }
}

This looks to me like your raycast is probably hitting your player itself.

1 Like

I tried adding a mesh collider to the LOD parent with the script and it’s still coming back null.

Also, this script is for picking up items so it should always be LOD0 simply because I’m limiting the range to 3 units.

Isn’t LOD based on scanline height?? I haven’t used it in so long I forget…

1 Like

OKAY WAIT!

I’m a complete moron!!!

I’m telling it to ignore only my layer. NOT to ignore everything BUT my layer.

Bit shift is still so confusing to me still.

Delete that one line of code that flips them and it works like a charm.

Never would have seen it without the log suggestion.

Thanks guys!

2 Likes

Pretty happy with the results:

Agreed… 10/10 would highlight again, definitely better than getting hit by a wooden club.

1 Like