Search code examples
c#unity-game-engineraycasting

Unity raycast not detecting an object which has already been detected by it before


using UnityEngine;

public class Shoot: MonoBehaviour

{

public Camera cam;

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        shooot();
    }
}

void shooot()
{
    RaycastHit hit;
    if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit))
    {
        Debug.Log(hit.transform.name);
    }
}

The other objects have a box collider and Rigid body. The Raycast detects "Cube1" and after I shoot a raycast at something else and then again shoot a raycast at "Cube1" this code does not detect it. Why?

img1

img2

img3


Solution

  • Unity does log everything. It's just that if you log the same output multiple times Unity collapses into one single line. You can see this by the number indicated on the right side of the output.

    (Image taken from https://learn.unity.com/tutorial/introduction-to-the-console-window#5f68b4eeedbc2a002022b83d) enter image description here

    If you toggle the marked "Collapse" button, it will show every single output.