Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Raytracing Hit on specific object error

Discussion in 'Scripting' started by barrylachapelle, Oct 22, 2015.

  1. barrylachapelle

    barrylachapelle

    Joined:
    Oct 22, 2015
    Posts:
    4
    Hi all!

    I am new to Unity and am trying to detect when the camera is looking at a specific object - a cube. I am using Physics.Raycast. I am getting an error "Object reference is not set to an instance of an object"

    Code (CSharp):
    1.         RaycastHit hit;
    2.  
    3.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    4.  
    5.         if (Physics.Raycast(ray, 100)) {
    6.             //print("Hit something");
    7.             if (hit.collider.gameObject.name == "CubeTrigger"){
    8.                 print("HIT CUBE!!!!!");
    9.             }
    10.  
    11.         }
    I have named the cube "CubeTrigger" in the inspector and turned its collider on as a trigger. Ive attached a screencap of the inspector with the cube selected and my console output.

    Any thoughts would be super appreciated.
     

    Attached Files:

  2. barrylachapelle

    barrylachapelle

    Joined:
    Oct 22, 2015
    Posts:
    4
    Hi everyone,

    Some progress on this! Again, I am trying to detect a Raycast on a specific object. These are the steps I have done so far...

    1. Drew a cube, named it CubeTrigger in the inspector
    2. Created a new script with the code above
    3. Added the script to the Cube by dragging it into the inspector with the3 cube selected

    I am now getting the error...

    Code (csharp):
    1.  
    2. Assets/Cardboard/DemoScene/Box.cs(21,42): error CS1061: Type `UnityEngine.Collider' does not contain a definition for `GameObject' and no extension method `GameObject' of type `UnityEngine.Collider' could be found (are you missing a using directive or an assembly reference?)
    3.  
    I think I am missing something very basic here and have read the getting started tuts but do not understand hwo to define aGameObject... is it more than naming in the inspector?

    Your help would be VERY appreciated.
     
  3. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,516
    The issue is that it's case sensitive. You're trying to use a variable called "GameObject" in your code, where in the collider it's called "gameObject".