#Item UI displaying issue

1 messages · Page 1 of 1 (latest)

vital shell
#

I have an issue, the way I showed UI above each item in my game before was using a raycast in each instance of TextVisible. I'm trying to make a new version that only uses one raycast.

hitSomething = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 4);
// if the raycast hits an item, get the items TextVisible script and set HitThis to true
// if the raycast is nolonger hitting that item, set it to false.```
I need a way to detect if the raycast is nolonger hitting the item it was previously, so I can disable the UI

I was thinking I might be able to save hit to a temp variable so I can disable HitThis if the player is not looking at the item anymore.

Something like this (but this doesnt work as it throws a null reference error in the if hit2 statement) 
```cs
hitSomething = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 4);
if (hitSomething)
{
    if (hit.collider.TryGetComponent(out TextVisible display))
    {
        display.hitThis = true;
    }
}
if (hit2.collider != hit.collider)
{
    if (hit2.collider.TryGetComponent(out TextVisible display))
    {
        display.hitThis = true;
    }
}
hit2 = hit;```
clear socket
vital shell
#

This is the line that is giving a null reference error

#

if (prevCollider.TryGetComponent(out TextVisible display))

#

Here's the updated code cs hitSomething = Physics.Raycast(Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)), out RaycastHit hit, 4); if (hitSomething) { if (hit.collider.TryGetComponent(out TextVisible display)) { display.hitThis = true; } } if (prevCollider != hit.collider) { if (prevCollider.TryGetComponent(out TextVisible display)) { display.hitThis = true; } } prevCollider = hit.collider;

#

I do notice that the error could be unimportant since I forgot to make display.hitThis = false in the second group

#

Nvm I was wrong, it seems the raycast is doing something wrong?

clear socket
vital shell
#

So I should assign it a value in the start method so it doesn't throw an exception?

clear socket
#

No. You should just make a null check and avoid accessing its members if it is null.