Questions about Raycasting?

Raycasting is really useful but can be tricky to understand. If you have any questions or observations about Raycasting, here is the place for them…

Id like to add a tip: raycasts dont tend to work if you start them inside a collider.

2 Likes

Good point, because you end up hitting the collider.

Since no one has said it yet, I just wanted to say: I appreciated the Austin Powers reference with the frickin’ laser beam.

6 Likes

please help me, i wrote down the exact same code yet it’s causing an issue

this is my code;

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

public class Mover : MonoBehaviour
{
[SerializeField] Transform target;

Ray lastRay;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        lastRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    }
    Debug.DrawRay(lastRay.origin, lastRay.direction * 100);

    GetComponent<NavMeshAgent>().destination = target.position;
        
}

}

So the issue according to the error is on line 16. Look at the logic on that line and make sure it is doing what it is expected to.

Just a heads up: Cause i was having tons of trouble with this, what was happenning is that my target was floating out of reach of my player and somehow this was preventing my raycasts from showing.

My code was identical but for some reason I can’t see the raycast at all. I added a debug line to make sure the left mouse button click was being registered. (It is.)

Then I tried adding the optional parameters (e.g. color, duration) and even lengthening the raycast (* 300 instead of 100). Still nothing.

Help!

I couldn’t get this to work for the longest time.
The Camera NEEDS to be tagged as MainCamera

Otherwise you get a NullReferenceException
I’m guessing I accidentally deleted the camera and put back another one.

3 Likes

Oh my! I feel so stupid right now…
Spent some 10 minutes pressing play, clicking, not working, stop. look at code, “should be working”, repeat.
Turns out I didn’t save the changes to my code :sweat_smile:

If I had a dollar for every time I’d done that… I could stop my day job! These things happen. It’s sort of an extra challenge when we’re using two different environments to create our programs (the Unity Editor and our code editor)

1 Like

If your rays aren’t showing up, make sure Gizmos are visible in the Scene and the Game view – do this by clicking the Gizmos button on each (when Gizmos are visible the button will appear lighter, darker otherwise) . To see the ray you will need to click in the Game view while it is running, and then the ray shows up in the Scene view, so you want to make sure your Scene view can see the camera and where you click – at least, that is how I was able to get it to work.

1 Like

I had the same problem, in my case I was an idiot and somehow didn’t type in the lastRay = part of the following.

“lastRay = Camera.main.ScreenPointToRay(Input.mousePosition);”

It alwasy seems to be silly errors causing me grief.

Hi Guys, thanks for these tutorials, I’ve finished the 3D beginners course and am working my way through this one now too, I’ve been working alongside the tutorials on a sneaking/stealth game, and have got the visual system working using raycasts from enemies, but could do with some help on the audio detection system, namely, is raycasting for audio echo/reflection around corners a sensible way of solving the ‘hearing thorugh walls’ problem when you just use a sphere trigger collider? I’ve linked my question on the forum with some more info. Cheers!

Same problem here! Was afraid I did something wrong, but it’s just as you said… Can only see the rays in scene view.

Would there be a difference/reasoning of using OnMouseDown versus Input.GetMouseButtonDown for registering the raycast in this case?

OnMouseDown would only fire on a script attached to the GameObject that is under the mouse cursor. It’s more of an event driven approach. It’s decentralized, so the PlayerController wouldn’t receive the events directly.
Input.GetMouseButtonDown(0) is an active polling of the state of the mouse button. This allows us to centralize our input in the PlayerController.

1 Like

You probably didnt set up the Tag of your camera it has to be the MainCamera tag. Sorry that im 1 year late for this xD but i had that same error. I think 90 percent of bugs are just things you havent set up in the inspector properly.

When I click on the branches (or the trunk) of a tree, instead of going behind them, the player moves to the base of the trunk, but to the opposite side.
And the behavior while holding down the left button is completely unpredictable if you come across an object like a house or a tree, in fact.

I created a specific layer for trees, so deselecting it in Inspector I should have ignored it, but it doesn’t work.
This is the code I’m using but it won’t work … HELP :frowning:

private bool InteractWithMovement()
        {
            int layer = (1 << layerMask);

            RaycastHit hit;
            bool hasHit = Physics.Raycast(GetMouseRay(), out hit, layer);
            if (hasHit)
            {
                if (Input.GetMouseButton(0))
                {
                    GetComponent<Movement.Mover>().StartMoveAction(hit.point, 1f);
                }
                return true;
            }
            return false;
        }

You can actually put a LayerMask in the inspector. It’s really just an integer, but Unity will picked it up and let you select layers in the inspector:

[SerializeField] LayerMask layerMask; //Just select the layers you want to hit in the inspector

then in your InteractWithMovement:

bool hasHit = Physics.Raycast(GetMouseRay(), out hit, layerMask);
1 Like